refactor: pyupgrade second iteration (#27451)

This commit is contained in:
Usama Sadiq
2021-05-10 13:46:28 +05:00
committed by GitHub
parent e7b8328620
commit 8c06b68bbe
13 changed files with 37 additions and 41 deletions

View File

@@ -28,4 +28,4 @@ class XMLParser(_XMLParser): # pylint: disable=function-redefined
def __init__(self, *args, **kwargs):
if "resolve_entities" not in kwargs:
kwargs["resolve_entities"] = False
super(XMLParser, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
super().__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments

View File

@@ -8,7 +8,6 @@
import math
import random
from six.moves import range
def lc_random(lower, upper, stepsize):

View File

@@ -27,7 +27,6 @@ values are (x, y) coordinates of centers of dragged images.
import json
import six
from six.moves import zip
def flat_user_answer(user_answer):
@@ -56,9 +55,9 @@ def flat_user_answer(user_answer):
v_value = list(v_value.values())[0]
complex_value_list.append(v_key)
complex_value = '{0}'.format(v_value)
complex_value = f'{v_value}'
for i in reversed(complex_value_list):
complex_value = '{0}[{1}]'.format(complex_value, i)
complex_value = f'{complex_value}[{i}]'
res = {key: complex_value}
return res
@@ -104,8 +103,8 @@ class PositionsCompare(list):
isinstance(other[0], (list, int, float))):
return self.coordinate_positions_compare(other)
elif (isinstance(self[0], (six.text_type, str)) and
isinstance(other[0], (six.text_type, str))):
elif (isinstance(self[0], (str, str)) and
isinstance(other[0], (str, str))):
return ''.join(self) == ''.join(other)
else: # improper argument types: no (float / int or lists of list
#and float / int pair) or two string / unicode lists pair
@@ -144,7 +143,7 @@ class PositionsCompare(list):
return True
class DragAndDrop(object):
class DragAndDrop:
""" Grader class for drag and drop inputtype.
"""
@@ -356,10 +355,10 @@ class DragAndDrop(object):
# correct_answer entries. If the draggable is mentioned in at least one
# correct_answer entry, the value is False.
# default to consider every user answer excess until proven otherwise.
self.excess_draggables = dict(
(list(users_draggable.keys())[0], True)
self.excess_draggables = {
list(users_draggable.keys())[0]: True
for users_draggable in user_answer
)
}
# Convert nested `user_answer` to flat format.
user_answer = flat_user_answer(user_answer)

View File

@@ -1,5 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Flexible python representation of a symbolic mathematical formula.
Acceptes Presentation MathML, Content MathML (and could also do OpenMath).
@@ -50,7 +49,7 @@ class dot(sympy.operations.LatticeOp): # pylint: disable=invalid-name, no-membe
def _print_dot(_self, expr):
"""Print statement used for LatexPrinter"""
return r'{((%s) \cdot (%s))}' % (expr.args[0], expr.args[1])
return fr'{{(({expr.args[0]}) \cdot ({expr.args[1]}))}}'
LatexPrinter._print_dot = _print_dot # pylint: disable=protected-access
@@ -175,7 +174,7 @@ def my_sympify(expr, normphase=False, matrix=False, abcsym=False, do_qubit=False
# class for symbolic mathematical formulas
class formula(object):
class formula:
"""
Representation of a mathematical formula object. Accepts mathml math expression
for constructing, and can produce sympy translation. The formula may or may not
@@ -210,7 +209,7 @@ class formula(object):
for k in xml:
tag = gettag(k)
if tag == 'mi' or tag == 'ci': # lint-amnesty, pylint: disable=consider-using-in
usym = six.text_type(k.text)
usym = str(k.text)
try:
udata = unicodedata.name(usym)
except Exception: # pylint: disable=broad-except
@@ -236,7 +235,7 @@ class formula(object):
it, if possible...
"""
if isinstance(xml, (str, six.text_type)):
if isinstance(xml, (str, str)):
xml = etree.fromstring(xml) # TODO: wrap in try
xml = self.fix_greek_in_mathml(xml) # convert greek utf letters to greek spelled out in ascii
@@ -369,13 +368,13 @@ class formula(object):
if (
tag == 'msup' and
len(k) == 2 and gettag(k[1]) == 'mrow' and
gettag(k[1][0]) == 'mo' and k[1][0].text == u'\u200b' # whew
gettag(k[1][0]) == 'mo' and k[1][0].text == '\u200b' # whew
):
# replace the msup with 'X__Y'
k[1].remove(k[1][0])
newk = etree.Element('mi')
newk.text = '%s__%s' % (flatten_pmathml(k[0]), flatten_pmathml(k[1]))
newk.text = f'{flatten_pmathml(k[0])}__{flatten_pmathml(k[1])}'
xml.replace(k, newk)
# match things like the middle example-
@@ -384,13 +383,13 @@ class formula(object):
if (
tag == 'msubsup' and
len(k) == 3 and gettag(k[2]) == 'mrow' and
gettag(k[2][0]) == 'mo' and k[2][0].text == u'\u200b' # whew
gettag(k[2][0]) == 'mo' and k[2][0].text == '\u200b' # whew
):
# replace the msubsup with 'X_Y__Z'
k[2].remove(k[2][0])
newk = etree.Element('mi')
newk.text = '%s_%s__%s' % (flatten_pmathml(k[0]), flatten_pmathml(k[1]), flatten_pmathml(k[2]))
newk.text = f'{flatten_pmathml(k[0])}_{flatten_pmathml(k[1])}__{flatten_pmathml(k[2])}'
xml.replace(k, newk)
fix_superscripts(k)
@@ -407,7 +406,7 @@ class formula(object):
if gettag(child) == 'msubsup' and len(child) == 3:
newchild = etree.Element('msup')
newbase = etree.Element('mi')
newbase.text = '%s_%s' % (flatten_pmathml(child[0]), flatten_pmathml(child[1]))
newbase.text = f'{flatten_pmathml(child[0])}_{flatten_pmathml(child[1])}'
newexp = child[2]
newchild.append(newbase)
newchild.append(newexp)
@@ -459,7 +458,7 @@ class formula(object):
if 'conversion from Presentation MathML to Content MathML was not successful' in cmml: # lint-amnesty, pylint: disable=unsupported-membership-test
msg = "Illegal math expression"
else:
msg = 'Err %s while converting cmathml to xml; cmml=%s' % (err, cmml)
msg = f'Err {err} while converting cmathml to xml; cmml={cmml}'
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
xml = self.fix_greek_in_mathml(xml)
self.the_sympy = self.make_sympy(xml[0])
@@ -545,7 +544,7 @@ class formula(object):
except Exception as err:
self.args = args # pylint: disable=attribute-defined-outside-init
self.op = op # pylint: disable=attribute-defined-outside-init, invalid-name
raise Exception('[formula] error=%s failed to apply %s to args=%s' % (err, opstr, args)) # lint-amnesty, pylint: disable=raise-missing-from
raise Exception(f'[formula] error={err} failed to apply {opstr} to args={args}') # lint-amnesty, pylint: disable=raise-missing-from
return res
else:
raise Exception('[formula]: unknown operator tag %s' % (opstr))
@@ -572,7 +571,7 @@ class formula(object):
usym = parse_presentation_symbol(xml[0])
sym = sympy.Symbol(str(usym))
else:
usym = six.text_type(xml.text)
usym = str(xml.text)
if 'hat' in usym:
sym = my_sympify(usym)
else:

View File

@@ -22,7 +22,7 @@ class FormulaTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-c
mathml_end = '</mstyle></math>'
def setUp(self):
super(FormulaTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
super().setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.formulaInstance = formula('')
def test_replace_mathvariants(self):

View File

@@ -1,7 +1,6 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from unittest import TestCase
from six.moves import range
from .symmath_check import symmath_check
@@ -81,9 +80,9 @@ class SymmathCheckTest(TestCase): # lint-amnesty, pylint: disable=missing-class
expect = n
ans = n
result = symmath_check(str(expect), str(ans))
assert (('ok' in result) and result['ok']), ('%f should == %f' % (expect, ans))
assert (('ok' in result) and result['ok']), (f'{expect:f} should == {ans:f}')
# Change expect so that it != ans
expect += 0.1
result = symmath_check(str(expect), str(ans))
assert (('ok' in result) and (not result['ok'])), ('%f should != %f' % (expect, ans))
assert (('ok' in result) and (not result['ok'])), (f'{expect:f} should != {ans:f}')

View File

@@ -458,7 +458,7 @@ class ContentStore:
except Exception as exc: # pylint: disable=broad-except
# log and continue as thumbnails are generally considered as optional
logging.exception(
"Failed to generate thumbnail for {}. Exception: {}".format(content.location, str(exc))
f"Failed to generate thumbnail for {content.location}. Exception: {str(exc)}"
)
return thumbnail_content, thumbnail_file_location

View File

@@ -1139,7 +1139,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
course_query = location.to_deprecated_son('_id.')
for key in course_query.keys():
if isinstance(course_query[key], str):
course_query[key] = re.compile(r"(?i)^{}$".format(course_query[key]))
course_query[key] = re.compile(fr"(?i)^{course_query[key]}$")
else:
course_query = {'_id': location.to_deprecated_son()}
course = self.collection.find_one(course_query, projection={'_id': True})
@@ -1346,7 +1346,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
if block_type == 'course':
block_id = course_key.run
else:
block_id = '{}_{}'.format(block_type, uuid4().hex[:5])
block_id = f'{block_type}_{uuid4().hex[:5]}'
if runtime is None:
services = {}
@@ -1411,7 +1411,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
if block_type == 'course':
block_id = course_key.run
else:
block_id = '{}_{}'.format(block_type, uuid4().hex[:5])
block_id = f'{block_type}_{uuid4().hex[:5]}'
runtime = kwargs.pop('runtime', None)
xblock = self.create_xblock(runtime, course_key, block_type, block_id, **kwargs)
@@ -1670,7 +1670,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
if len(non_orphan_parents) > 1: # lint-amnesty, pylint: disable=no-else-raise
# should never have multiple PUBLISHED parents
raise ReferentialIntegrityError(
"{} parents claim {}".format(len(parents), location)
f"{len(parents)} parents claim {location}"
)
else:
return cache_and_return(non_orphan_parents[0].replace(run=location.course_key.run))

View File

@@ -90,7 +90,7 @@ class Tagger:
and also all of the added measurements, bucketed into powers of 2).
"""
return [
'{}:{}'.format(name, round_power_2(size))
f'{name}:{round_power_2(size)}'
for name, size in self.measures
] + [
f'{name}:{value}'
@@ -427,7 +427,7 @@ class MongoConnection:
with TIMER.timer("get_course_index", key):
if ignore_case:
query = {
key_attr: re.compile('^{}$'.format(re.escape(getattr(key, key_attr))), re.IGNORECASE)
key_attr: re.compile(f'^{re.escape(getattr(key, key_attr))}$', re.IGNORECASE)
for key_attr in ('org', 'course', 'run')
}
else:

View File

@@ -1064,7 +1064,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
if len(course_block) > 1:
raise MultipleCourseBlocksFound(
"Expected 1 course block to be found in the course, but found {}".format(len(course_block))
f"Expected 1 course block to be found in the course, but found {len(course_block)}"
)
course_summary = extract_course_summary(course_block[0])
courses_summaries.append(
@@ -1106,7 +1106,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
if len(library_block) > 1:
raise MultipleLibraryBlocksFound(
"Expected 1 library block, but found {}".format(len(library_block))
f"Expected 1 library block, but found {len(library_block)}"
)
library_block_fields = library_block[0].fields

View File

@@ -607,14 +607,14 @@ def check_sum_of_calls(object_, methods, maximum_calls, minimum_calls=1, include
stack_counter.total_calls
))
for stack in stack_counter:
messages.append(" called {} times:\n\n".format(stack_counter.stack_calls(stack)))
messages.append(f" called {stack_counter.stack_calls(stack)} times:\n\n")
messages.append(" " + " ".join(traceback.format_list(stack)))
messages.append("\n\n")
if include_arguments:
for (args, kwargs), count in stack_counter[stack].items():
messages.append(f" called {count} times with:\n")
messages.append(f" args: {args}\n")
messages.append(" kwargs: {}\n\n".format(dict(kwargs)))
messages.append(f" kwargs: {dict(kwargs)}\n\n")
# verify that we called the methods within the desired range
assert minimum_calls <= call_count <= maximum_calls, "".join(messages)

View File

@@ -2450,7 +2450,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
assert store.get_modulestore_type() == store_type
# verify store used for creating a course
course = self.store.create_course("org", "course{}".format(uuid4().hex[:5]), "run", self.user_id)
course = self.store.create_course("org", f"course{uuid4().hex[:5]}", "run", self.user_id)
assert course.system.modulestore.get_modulestore_type() == store_type
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)

View File

@@ -102,7 +102,7 @@ class MixedSplitTestCase(TestCase):
Stripped-down version of ModuleStoreTestCase that can be used without Django
(i.e. for testing in common/lib/ ). Sets up MixedModuleStore and Split.
"""
RENDER_TEMPLATE = lambda t_n, d, ctx=None, nsp='main': '{}: {}, {}'.format(t_n, repr(d), repr(ctx))
RENDER_TEMPLATE = lambda t_n, d, ctx=None, nsp='main': f'{t_n}: {repr(d)}, {repr(ctx)}'
modulestore_options = {
'default_class': 'xmodule.hidden_module.HiddenDescriptor',
'fs_root': DATA_DIR,