refactor: pyupgrade second iteration (#27459)

This commit is contained in:
Usama Sadiq
2021-05-10 13:56:40 +05:00
committed by GitHub
parent 372c4abfa6
commit 64752ed66c
14 changed files with 37 additions and 37 deletions

View File

@@ -50,5 +50,5 @@ def cursor_paginate_serializer(inner_serializer_class):
help_text="The list of result objects on this page.",
)
PageOfInnerSerializer.__name__ = 'PageOf{}'.format(inner_serializer_class.__name__)
PageOfInnerSerializer.__name__ = f'PageOf{inner_serializer_class.__name__}'
return PageOfInnerSerializer

View File

@@ -162,7 +162,7 @@ def get_xblock_id_for_anonymous_user(user):
if current_request and current_request.session:
# Make sure we have a key for this user:
if "xblock_id_for_anonymous_user" not in current_request.session:
new_id = "anon{}".format(uuid4().hex[:20])
new_id = f"anon{uuid4().hex[:20]}"
current_request.session["xblock_id_for_anonymous_user"] = new_id
return current_request.session["xblock_id_for_anonymous_user"]
else:

View File

@@ -68,7 +68,7 @@ class TypedFileUploadParser(FileUploadParser):
if len(fileparts) < 2:
ext = ''
else:
ext = '.{}'.format(fileparts[1])
ext = f'.{fileparts[1]}'
if ext.lower() not in self.file_extensions[media_type]:
errmsg = (
'File extension does not match requested Content-type. '

View File

@@ -425,7 +425,7 @@ def verify_course_exists(view_func):
if not CourseOverview.course_exists(course_key):
raise self.api_error(
status_code=status.HTTP_404_NOT_FOUND,
developer_message="Requested grade for unknown course {course}".format(course=str(course_key)),
developer_message=f"Requested grade for unknown course {str(course_key)}",
error_code='course_does_not_exist'
)

View File

@@ -46,4 +46,4 @@ def parse_course_keys(course_key_strings):
try:
return [CourseKey.from_string(course_key_string) for course_key_string in course_key_strings]
except InvalidKeyError as error:
raise CommandError('Invalid key specified: {}'.format(str(error))) # lint-amnesty, pylint: disable=raise-missing-from
raise CommandError(f'Invalid key specified: {str(error)}') # lint-amnesty, pylint: disable=raise-missing-from

View File

@@ -79,7 +79,7 @@ def clean_course_id(model_form, is_required=True):
raise forms.ValidationError(msg) # lint-amnesty, pylint: disable=raise-missing-from
if not modulestore().has_course(course_key):
msg = 'Course not found. Entered course id was: "{}".'.format(str(course_key))
msg = f'Course not found. Entered course id was: "{str(course_key)}".'
raise forms.ValidationError(msg)
return course_key
@@ -98,4 +98,4 @@ def get_course_by_id(course_key, depth=0):
if course:
return course
else:
raise Http404("Course not found: {}.".format(str(course_key)))
raise Http404(f"Course not found: {str(course_key)}.")

View File

@@ -33,7 +33,7 @@ class TeamsConfig: # pylint: disable=eq-without-hash
TODO move this code to __str__ after Py3 upgrade.
"""
return "Teams configuration for {} team-sets".format(len(self.teamsets))
return f"Teams configuration for {len(self.teamsets)} team-sets"
def __str__(self):
"""

View File

@@ -223,11 +223,11 @@ def compare_structs(expected, actual, should_strict_compare=None, path=None):
actual_keys = frozenset(list(actual.keys()))
for key in expected_keys - actual_keys:
differences.append('{}: not found in actual'.format(_path_to_string(path + [key])))
differences.append(f'{_path_to_string(path + [key])}: not found in actual')
if should_strict_compare is not None and should_strict_compare(path):
for key in actual_keys - expected_keys:
differences.append('{}: only defined in actual'.format(_path_to_string(path + [key])))
differences.append(f'{_path_to_string(path + [key])}: only defined in actual')
for key in expected_keys & actual_keys:
child_differences = compare_structs(expected[key], actual[key], should_strict_compare, path + [key])

View File

@@ -105,7 +105,7 @@ def wrap_xblock(
css_classes = [
'xblock',
'xblock-{}'.format(markupsafe.escape(view)),
f'xblock-{markupsafe.escape(view)}',
'xblock-{}-{}'.format(
markupsafe.escape(view),
markupsafe.escape(block.scope_ids.block_type),
@@ -147,7 +147,7 @@ def wrap_xblock(
'content': block.display_name if display_name_only else frag.content,
'classes': css_classes,
'display_name': block.display_name_with_default_escaped, # xss-lint: disable=python-deprecated-display-name
'data_attributes': ' '.join('data-{}="{}"'.format(markupsafe.escape(key), markupsafe.escape(value))
'data_attributes': ' '.join(f'data-{markupsafe.escape(key)}="{markupsafe.escape(value)}"'
for key, value in data.items()),
}
@@ -198,7 +198,7 @@ def wrap_xblock_aside(
data.update(extra_data)
css_classes = [
'xblock-{}'.format(markupsafe.escape(view)),
f'xblock-{markupsafe.escape(view)}',
'xblock-{}-{}'.format(
markupsafe.escape(view),
markupsafe.escape(aside.scope_ids.block_type),
@@ -220,7 +220,7 @@ def wrap_xblock_aside(
template_context = {
'content': frag.content,
'classes': css_classes,
'data_attributes': ' '.join('data-{}="{}"'.format(markupsafe.escape(key), markupsafe.escape(value))
'data_attributes': ' '.join(f'data-{markupsafe.escape(key)}="{markupsafe.escape(value)}"'
for key, value in data.items()),
}

View File

@@ -102,7 +102,7 @@ def read_warning_data(dir_path):
# go through each warning file and aggregate warnings into warnings_data
warnings_data = []
for temp_file in warnings_files:
with io.open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file:
with open(os.path.expanduser(dir_path + "/" + temp_file), "r") as read_file:
json_input = json.load(read_file)
if "warnings" in json_input:
data = [
@@ -183,17 +183,17 @@ def write_html_report(warnings_data, html_path):
location_of_last_dir = html_path.rfind("/")
dir_path = html_path[:location_of_last_dir]
os.makedirs(dir_path, exist_ok=True)
with io.open(html_path, "w") as fout:
with open(html_path, "w") as fout:
html_writer = HtmlOutlineWriter(fout)
category_sorted_by_count = group_and_sort_by_sumof(
warnings_data, "category", "num"
)
for category, group_in_category, category_count in category_sorted_by_count:
# xss-lint: disable=python-wrap-html
html = u'<span class="count">{category}, count: {count}</span> '.format(
html = '<span class="count">{category}, count: {count}</span> '.format(
category=category, count=category_count
)
html_writer.start_section(html, klass=u"category")
html_writer.start_section(html, klass="category")
locations_sorted_by_count = group_and_sort_by_sumof(
group_in_category, "high_location", "num"
)
@@ -204,10 +204,10 @@ def write_html_report(warnings_data, html_path):
location_count,
) in locations_sorted_by_count:
# xss-lint: disable=python-wrap-html
html = u'<span class="count">{location}, count: {count}</span> '.format(
html = '<span class="count">{location}, count: {count}</span> '.format(
location=location, count=location_count
)
html_writer.start_section(html, klass=u"location")
html_writer.start_section(html, klass="location")
message_group_sorted_by_count = group_and_sort_by_sumof(
group_in_location, "message", "num"
)
@@ -217,24 +217,24 @@ def write_html_report(warnings_data, html_path):
message_count,
) in message_group_sorted_by_count:
# xss-lint: disable=python-wrap-html
html = u'<span class="count">{warning_text}, count: {count}</span> '.format(
html = '<span class="count">{warning_text}, count: {count}</span> '.format(
warning_text=message, count=message_count
)
html_writer.start_section(html, klass=u"warning_text")
html_writer.start_section(html, klass="warning_text")
# warnings_object[location][warning_text] is a list
for warning in message_group:
# xss-lint: disable=python-wrap-html
html = u'<span class="count">{warning_file_path}</span> '.format(
html = '<span class="count">{warning_file_path}</span> '.format(
warning_file_path=warning[columns_index_dict["filename"]]
)
html_writer.start_section(html, klass=u"warning")
html_writer.start_section(html, klass="warning")
# xss-lint: disable=python-wrap-html
html = u'<p class="lineno">lineno: {lineno}</p> '.format(
html = '<p class="lineno">lineno: {lineno}</p> '.format(
lineno=warning[columns_index_dict["lineno"]]
)
html_writer.write(html)
# xss-lint: disable=python-wrap-html
html = u'<p class="num">num_occur: {num}</p> '.format(
html = '<p class="num">num_occur: {num}</p> '.format(
num=warning[columns_index_dict["num"]]
)
html_writer.write(html)

View File

@@ -58,11 +58,11 @@ def pytest_sessionfinish(session):
report = session.config._json_report.report # noqa pylint: disable=protected-access
with io.open(create_file_name(dir_path, file_name_postfix, num), "w") as outfile:
with open(create_file_name(dir_path, file_name_postfix, num), "w") as outfile:
json.dump(report, outfile)
class DeferPlugin(object):
class DeferPlugin:
"""Simple plugin to defer pytest-xdist hook functions."""
def pytest_json_modifyreport(self, json_report):

View File

@@ -19,7 +19,7 @@ def doc_version():
if RELEASE_LINE == "master":
return "latest"
else:
return "open-release-{}.master".format(RELEASE_LINE)
return f"open-release-{RELEASE_LINE}.master"
def skip_unless_master(func_or_class):

View File

@@ -15,13 +15,13 @@ from storages.backends.s3boto3 import S3Boto3Storage
from openedx.core.djangoapps.theming.storage import ThemeManifestFilesMixin, ThemePipelineMixin, ThemeMixin
class PipelineForgivingMixin(object):
class PipelineForgivingMixin:
"""
An extension of the django-pipeline storage backend which forgives missing files.
"""
def hashed_name(self, name, content=None, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring
try:
out = super(PipelineForgivingMixin, self).hashed_name(name, content, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
out = super().hashed_name(name, content, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
except ValueError:
# This means that a file could not be found, and normally this would
# cause a fatal error, which seems rather excessive given that
@@ -31,7 +31,7 @@ class PipelineForgivingMixin(object):
def stored_name(self, name): # lint-amnesty, pylint: disable=missing-function-docstring
try:
out = super(PipelineForgivingMixin, self).stored_name(name) # lint-amnesty, pylint: disable=super-with-arguments
out = super().stored_name(name) # lint-amnesty, pylint: disable=super-with-arguments
except ValueError:
# This means that a file could not be found, and normally this would
# cause a fatal error, which seems rather excessive given that
@@ -54,7 +54,7 @@ class ProductionMixin(
"""
def __init__(self, *args, **kwargs):
kwargs.update(settings.STATICFILES_STORAGE_KWARGS.get(settings.STATICFILES_STORAGE, {}))
super(ProductionMixin, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
super().__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
class ProductionStorage(ProductionMixin, StaticFilesStorage):

View File

@@ -5,12 +5,12 @@ import textwrap
import six
class HtmlOutlineWriter(object):
class HtmlOutlineWriter:
"""
writer to handle html writing
"""
HEAD = textwrap.dedent(
u"""
"""
<!DOCTYPE html>
<html>
<head>
@@ -70,7 +70,7 @@ class HtmlOutlineWriter(object):
)
SECTION_START = textwrap.dedent(
u"""\
"""\
<div class="{klass}">
<input class="toggle-box {klass}" id="sect_{id:05d}" type="checkbox">
<label for="sect_{id:05d}">{html}</label>
@@ -78,7 +78,7 @@ class HtmlOutlineWriter(object):
"""
)
SECTION_END = six.u("</div></div>")
SECTION_END = "</div></div>"
def __init__(self, fout):
self.fout = fout