refactor: pyupgrade second iteration (#27450)
This commit is contained in:
@@ -625,7 +625,7 @@ class ProblemBlock(
|
||||
minimal_init=True,
|
||||
)
|
||||
except responsetypes.LoncapaProblemError:
|
||||
log.exception("LcpFatalError for block {} while getting max score".format(str(self.location)))
|
||||
log.exception(f"LcpFatalError for block {str(self.location)} while getting max score")
|
||||
maximum_score = 0
|
||||
else:
|
||||
maximum_score = lcp.get_max_score()
|
||||
@@ -903,7 +903,7 @@ class ProblemBlock(
|
||||
})
|
||||
|
||||
def handle_fatal_lcp_error(self, error): # lint-amnesty, pylint: disable=missing-function-docstring
|
||||
log.exception("LcpFatalError Encountered for {block}".format(block=str(self.location)))
|
||||
log.exception(f"LcpFatalError Encountered for {str(self.location)}")
|
||||
if error:
|
||||
return(
|
||||
HTML('<p>Error formatting HTML for problem:</p><p><pre style="color:red">{msg}</pre></p>').format(
|
||||
@@ -1633,7 +1633,7 @@ class ProblemBlock(
|
||||
# If the submission wasn't deserializable, raise an error.
|
||||
except(KeyError, ValueError):
|
||||
raise ValueError( # lint-amnesty, pylint: disable=raise-missing-from
|
||||
"Invalid submission: {val} for {key}".format(val=data[key], key=key)
|
||||
f"Invalid submission: {data[key]} for {key}"
|
||||
)
|
||||
else:
|
||||
val = data[key]
|
||||
@@ -1784,7 +1784,7 @@ class ProblemBlock(
|
||||
self.set_score(self.score_from_lcp(self.lcp))
|
||||
|
||||
if self.runtime.DEBUG:
|
||||
msg = "Error checking problem: {}".format(str(err))
|
||||
msg = f"Error checking problem: {str(err)}"
|
||||
msg += f'\nTraceback:\n{traceback.format_exc()}'
|
||||
return {'success': msg}
|
||||
raise
|
||||
|
||||
@@ -1059,7 +1059,7 @@ class CourseBlock(
|
||||
if not getattr(self, "tabs", []):
|
||||
CourseTabList.initialize_default(self)
|
||||
except InvalidTabsException as err:
|
||||
raise type(err)('{msg} For course: {course_id}'.format(msg=str(err), course_id=str(self.id))) # lint-amnesty, pylint: disable=line-too-long
|
||||
raise type(err)(f'{str(err)} For course: {str(self.id)}') # lint-amnesty, pylint: disable=line-too-long
|
||||
|
||||
self.set_default_certificate_available_date()
|
||||
|
||||
|
||||
@@ -292,7 +292,7 @@ class LTI20BlockMixin:
|
||||
try:
|
||||
self.verify_oauth_body_sign(request, content_type=LTI_2_0_JSON_CONTENT_TYPE)
|
||||
except (ValueError, LTIError) as err:
|
||||
log.info("[LTI]: v2.0 result service -- OAuth body verification failed: {}".format(str(err)))
|
||||
log.info(f"[LTI]: v2.0 result service -- OAuth body verification failed: {str(err)}")
|
||||
raise LTIError(str(err)) # lint-amnesty, pylint: disable=raise-missing-from
|
||||
|
||||
def parse_lti_2_0_result_json(self, json_str):
|
||||
@@ -362,7 +362,7 @@ class LTI20BlockMixin:
|
||||
log.info(f"[LTI] {msg}")
|
||||
raise LTIError(msg)
|
||||
except (TypeError, ValueError) as err:
|
||||
msg = "Could not convert resultScore to float: {}".format(str(err))
|
||||
msg = f"Could not convert resultScore to float: {str(err)}"
|
||||
log.info(f"[LTI] {msg}")
|
||||
raise LTIError(msg) # lint-amnesty, pylint: disable=raise-missing-from
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ def rewrite_nonportable_content_links(source_course_id, dest_course_id, text):
|
||||
#
|
||||
if source_course_id != dest_course_id:
|
||||
try:
|
||||
generic_courseware_link_base = '/courses/{}/'.format(str(source_course_id))
|
||||
generic_courseware_link_base = f'/courses/{str(source_course_id)}/'
|
||||
text = re.sub(_prefix_only_url_replace_regex(generic_courseware_link_base), portable_asset_link_subtitution, text) # lint-amnesty, pylint: disable=line-too-long
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", source_course_id, text, str(exc)) # lint-amnesty, pylint: disable=line-too-long
|
||||
|
||||
@@ -266,7 +266,7 @@ class CourseLocationManager(OpaqueKeyReader, AsideKeyGenerator):
|
||||
def create_definition(self, block_type, slug=None):
|
||||
assert block_type is not None
|
||||
if slug is None:
|
||||
slug = 'autogen_{}_{}'.format(block_type, next(self.autogen_ids))
|
||||
slug = f'autogen_{block_type}_{next(self.autogen_ids)}'
|
||||
return self.course_id.make_usage_key(block_type, slug)
|
||||
|
||||
def get_definition_id(self, usage_id):
|
||||
|
||||
@@ -971,7 +971,7 @@ def _import_course_draft(
|
||||
# Skip any OSX quarantine files, prefixed with a '._'.
|
||||
continue
|
||||
module_path = os.path.join(rootdir, filename)
|
||||
with open(module_path, 'r') as f:
|
||||
with open(module_path) as f:
|
||||
try:
|
||||
xml = f.read()
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ class Progress: # pylint: disable=eq-without-hash
|
||||
'''
|
||||
(a, b) = self.frac()
|
||||
display = lambda n: f'{n:.2f}'.rstrip('0').rstrip('.')
|
||||
return "{}/{}".format(display(a), display(b))
|
||||
return f"{display(a)}/{display(b)}"
|
||||
|
||||
@staticmethod
|
||||
def add_counts(a, b):
|
||||
|
||||
@@ -112,7 +112,7 @@ class SequenceMixin(SequenceFields):
|
||||
except Exception as e: # pylint: disable=broad-except
|
||||
log.exception("Unable to load child when parsing Sequence. Continuing...")
|
||||
if system.error_tracker is not None:
|
||||
system.error_tracker(u"ERROR: {0}".format(e))
|
||||
system.error_tracker(f"ERROR: {e}")
|
||||
continue
|
||||
return {}, children
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class SettingsService:
|
||||
def get_settings_bucket(self, block, default=None):
|
||||
""" Gets xblock settings dictionary from settings. """
|
||||
if not block:
|
||||
raise ValueError("Expected XBlock instance, got {} of type {}".format(block, type(block)))
|
||||
raise ValueError(f"Expected XBlock instance, got {block} of type {type(block)}")
|
||||
|
||||
actual_default = default if default is not None else {}
|
||||
xblock_settings_bucket = getattr(block, self.xblock_settings_bucket_selector, block.unmixed_class.__name__)
|
||||
|
||||
@@ -279,7 +279,7 @@ class ConditionalBlockXmlTest(unittest.TestCase):
|
||||
'conditional_ajax.html',
|
||||
{
|
||||
# Test ajax url is just usage-id / handler_name
|
||||
'ajax_url': '{}/xmodule_handler'.format(str(location)),
|
||||
'ajax_url': f'{str(location)}/xmodule_handler',
|
||||
'element_id': 'i4x-HarvardX-ER22x-conditional-condone',
|
||||
'depends': 'i4x-HarvardX-ER22x-problem-choiceprob'
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ def strip_filenames(descriptor):
|
||||
"""
|
||||
Recursively strips 'filename' from all children's definitions.
|
||||
"""
|
||||
print("strip filename from {desc}".format(desc=str(descriptor.location)))
|
||||
print(f"strip filename from {str(descriptor.location)}")
|
||||
if descriptor._field_data.has(descriptor, 'filename'): # lint-amnesty, pylint: disable=protected-access
|
||||
descriptor._field_data.delete(descriptor, 'filename') # lint-amnesty, pylint: disable=protected-access
|
||||
|
||||
|
||||
@@ -439,7 +439,7 @@ class ImportTestCase(BaseCourseTestCase): # lint-amnesty, pylint: disable=missi
|
||||
|
||||
def check_for_key(key, node, value):
|
||||
"recursive check for presence of key"
|
||||
print("Checking {}".format(str(node.location)))
|
||||
print(f"Checking {str(node.location)}")
|
||||
assert getattr(node, key) == value
|
||||
for c in node.get_children():
|
||||
check_for_key(key, c, value)
|
||||
|
||||
@@ -46,11 +46,11 @@ class SequenceBlockTestCase(XModuleXmlImportTest):
|
||||
|
||||
for chapter_index in range(len(self.course.get_children())):
|
||||
chapter = self._set_up_block(self.course, chapter_index)
|
||||
setattr(self, 'chapter_{}'.format(chapter_index + 1), chapter)
|
||||
setattr(self, f'chapter_{chapter_index + 1}', chapter)
|
||||
|
||||
for sequence_index in range(len(chapter.get_children())):
|
||||
sequence = self._set_up_block(chapter, sequence_index)
|
||||
setattr(self, 'sequence_{}_{}'.format(chapter_index + 1, sequence_index + 1), sequence)
|
||||
setattr(self, f'sequence_{chapter_index + 1}_{sequence_index + 1}', sequence)
|
||||
|
||||
@staticmethod
|
||||
def _set_up_course_xml():
|
||||
|
||||
@@ -136,7 +136,7 @@ class VerticalBlockTestCase(BaseVerticalBlockTest):
|
||||
Assert content has/hasn't all the bookmark info.
|
||||
"""
|
||||
assertion('bookmark_id', content)
|
||||
assertion('{},{}'.format(self.username, str(self.vertical.location)), content)
|
||||
assertion(f'{self.username},{str(self.vertical.location)}', content)
|
||||
assertion('bookmarked', content)
|
||||
assertion('show_bookmark_button', content)
|
||||
|
||||
@@ -180,8 +180,8 @@ class VerticalBlockTestCase(BaseVerticalBlockTest):
|
||||
if context:
|
||||
assert "'has_assignments': True" in html
|
||||
assert "'subsection_format': '{}'".format(context['format']) in html
|
||||
assert "'completed': {}".format(completion_value == 1) in html
|
||||
assert "'past_due': {}".format(self.vertical.due < now) in html
|
||||
assert f"'completed': {completion_value == 1}" in html
|
||||
assert f"'past_due': {self.vertical.due < now}" in html
|
||||
|
||||
@ddt.data(True, False)
|
||||
def test_render_problem_without_score(self, has_score):
|
||||
|
||||
@@ -109,7 +109,7 @@ class InheritingFieldDataTest(unittest.TestCase):
|
||||
"""
|
||||
scope_ids = Mock()
|
||||
if usage_id is None:
|
||||
block_id = "_auto{id}".format(id=len(self.all_blocks))
|
||||
block_id = f"_auto{len(self.all_blocks)}"
|
||||
usage_id = self.get_usage_id("course", block_id)
|
||||
scope_ids.usage_id = usage_id
|
||||
block = self.system.construct_xblock_from_class(
|
||||
|
||||
@@ -1023,7 +1023,7 @@ class VideoBlock(
|
||||
""" Find video transcript - if not found, don't update index """
|
||||
try:
|
||||
transcript = get_transcript(self, lang=language, output_format=Transcript.TXT)[0].replace("\n", " ")
|
||||
transcript_index_name = "transcript_{}".format(language if language else self.transcript_language)
|
||||
transcript_index_name = f"transcript_{language if language else self.transcript_language}"
|
||||
video_body.update({transcript_index_name: transcript})
|
||||
except NotFoundError:
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user