From 64752ed66c69c57898b60d5a187c5a5a4e1e13ae Mon Sep 17 00:00:00 2001 From: Usama Sadiq Date: Mon, 10 May 2021 13:56:40 +0500 Subject: [PATCH] refactor: pyupgrade second iteration (#27459) --- openedx/core/apidocs.py | 2 +- openedx/core/djangoapps/xblock/utils.py | 2 +- openedx/core/lib/api/parsers.py | 2 +- openedx/core/lib/api/view_utils.py | 2 +- openedx/core/lib/command_utils.py | 2 +- openedx/core/lib/courses.py | 4 ++-- openedx/core/lib/teams_config.py | 2 +- openedx/core/lib/tests/assertions/events.py | 4 ++-- openedx/core/lib/xblock_utils/__init__.py | 8 +++---- openedx/core/process_warnings.py | 24 ++++++++++----------- openedx/core/pytest_hooks.py | 4 ++-- openedx/core/release.py | 2 +- openedx/core/storage.py | 8 +++---- openedx/core/write_to_html.py | 8 +++---- 14 files changed, 37 insertions(+), 37 deletions(-) diff --git a/openedx/core/apidocs.py b/openedx/core/apidocs.py index 3651a2162c..e44c5f6e6b 100644 --- a/openedx/core/apidocs.py +++ b/openedx/core/apidocs.py @@ -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 diff --git a/openedx/core/djangoapps/xblock/utils.py b/openedx/core/djangoapps/xblock/utils.py index 901598e010..375bb9d214 100644 --- a/openedx/core/djangoapps/xblock/utils.py +++ b/openedx/core/djangoapps/xblock/utils.py @@ -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: diff --git a/openedx/core/lib/api/parsers.py b/openedx/core/lib/api/parsers.py index fc42aab8b8..d4037172b4 100644 --- a/openedx/core/lib/api/parsers.py +++ b/openedx/core/lib/api/parsers.py @@ -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. ' diff --git a/openedx/core/lib/api/view_utils.py b/openedx/core/lib/api/view_utils.py index 8ceaae7e0e..400004db8e 100644 --- a/openedx/core/lib/api/view_utils.py +++ b/openedx/core/lib/api/view_utils.py @@ -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' ) diff --git a/openedx/core/lib/command_utils.py b/openedx/core/lib/command_utils.py index 3510170de5..dd9936f5dd 100644 --- a/openedx/core/lib/command_utils.py +++ b/openedx/core/lib/command_utils.py @@ -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 diff --git a/openedx/core/lib/courses.py b/openedx/core/lib/courses.py index f81bff03c6..d46dc65c18 100644 --- a/openedx/core/lib/courses.py +++ b/openedx/core/lib/courses.py @@ -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)}.") diff --git a/openedx/core/lib/teams_config.py b/openedx/core/lib/teams_config.py index 145625f255..658b108a1c 100644 --- a/openedx/core/lib/teams_config.py +++ b/openedx/core/lib/teams_config.py @@ -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): """ diff --git a/openedx/core/lib/tests/assertions/events.py b/openedx/core/lib/tests/assertions/events.py index 1aeaeb36d5..65d1fffdb3 100644 --- a/openedx/core/lib/tests/assertions/events.py +++ b/openedx/core/lib/tests/assertions/events.py @@ -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]) diff --git a/openedx/core/lib/xblock_utils/__init__.py b/openedx/core/lib/xblock_utils/__init__.py index 0eaa4f437f..460c2c8034 100644 --- a/openedx/core/lib/xblock_utils/__init__.py +++ b/openedx/core/lib/xblock_utils/__init__.py @@ -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()), } diff --git a/openedx/core/process_warnings.py b/openedx/core/process_warnings.py index fb6a3da738..331816d196 100644 --- a/openedx/core/process_warnings.py +++ b/openedx/core/process_warnings.py @@ -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'{category}, count: {count} '.format( + html = '{category}, count: {count} '.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'{location}, count: {count} '.format( + html = '{location}, count: {count} '.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'{warning_text}, count: {count} '.format( + html = '{warning_text}, count: {count} '.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'{warning_file_path} '.format( + html = '{warning_file_path} '.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'

lineno: {lineno}

'.format( + html = '

lineno: {lineno}

'.format( lineno=warning[columns_index_dict["lineno"]] ) html_writer.write(html) # xss-lint: disable=python-wrap-html - html = u'

num_occur: {num}

'.format( + html = '

num_occur: {num}

'.format( num=warning[columns_index_dict["num"]] ) html_writer.write(html) diff --git a/openedx/core/pytest_hooks.py b/openedx/core/pytest_hooks.py index 211680d362..1552b39496 100644 --- a/openedx/core/pytest_hooks.py +++ b/openedx/core/pytest_hooks.py @@ -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): diff --git a/openedx/core/release.py b/openedx/core/release.py index 6aa63d17d0..ce30df8cc5 100644 --- a/openedx/core/release.py +++ b/openedx/core/release.py @@ -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): diff --git a/openedx/core/storage.py b/openedx/core/storage.py index a016915c31..4e2f0643ed 100644 --- a/openedx/core/storage.py +++ b/openedx/core/storage.py @@ -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): diff --git a/openedx/core/write_to_html.py b/openedx/core/write_to_html.py index 108ea179a9..aa35b8a575 100644 --- a/openedx/core/write_to_html.py +++ b/openedx/core/write_to_html.py @@ -5,12 +5,12 @@ import textwrap import six -class HtmlOutlineWriter(object): +class HtmlOutlineWriter: """ writer to handle html writing """ HEAD = textwrap.dedent( - u""" + """ @@ -70,7 +70,7 @@ class HtmlOutlineWriter(object): ) SECTION_START = textwrap.dedent( - u"""\ + """\
@@ -78,7 +78,7 @@ class HtmlOutlineWriter(object): """ ) - SECTION_END = six.u("
") + SECTION_END = "" def __init__(self, fout): self.fout = fout