Skip to content

Commit

Permalink
Merge pull request #25 from edx/jenkins/cleanup-python-code-61df1b1
Browse files Browse the repository at this point in the history
Python Code Cleanup
  • Loading branch information
UsamaSadiq authored Jan 21, 2021
2 parents 61df1b1 + 9993047 commit 193afec
Show file tree
Hide file tree
Showing 12 changed files with 89 additions and 99 deletions.
21 changes: 10 additions & 11 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,29 @@ language: python
sudo: false
cache: pip
python:
- 3.5
- 3.8
- '3.8'
env:
- TOXENV=py3
- TOXENV=py38
- TOXENV=quality
addons:
apt:
packages:
- libblas-dev
- liblapack-dev
- gfortran
- libblas-dev
- liblapack-dev
- gfortran
install:
- pip install -r requirements/travis.txt
- pip install -r requirements/travis.txt
script:
- make test
- make test
after_success:
- coveralls
- coveralls
deploy:
provider: pypi
user: edx
distributions: sdist bdist_wheel
on:
tags: true
python: 3.5
condition: "$TOXENV = quality"
python: 3.8
condition: $TOXENV = quality
password:
secure: Jr+k3Aw8cGRY9s7w1vpbxnRKVJPnxOl1ZW3mygzhDexEtwUTCI1jIT3dT7uUwsXr2NJP2bN9DsRXOF/+4zPZrSyx73JgKPQrlq/7BIYIYZl89kXol7033edo33da+CkpsExJGw92+f3riHojn5PGCpuoI0ITKRls/nmuB5J3aCJ4jXMkJo8RNUT5xSrdOSYf718HQSb1skA2LLri38ZMS9ld1aaKX2oqY3uVEHE67UX79Q8CUwLV5TMvDiU2kjqbM9NcIdw8Isu7WSSH1c5d4PJq36Sw7kEUyJ6HP/evB3Wln3j7DJfp9d5dQF6HAt0vsA4dzyzCaefTnJKbCAhAm7yCi7jGiH7UHQyiCq8RX8+rUsNEE5nr46XgCvgFDDBZ+BHN8b0oilXa9E4TUCBQgReNYzoJyFXcF355Etlz7Nq1aPkDPz4jPKEJFDKuMeTsBqZZLSWIFS4E7CW3yH12XRrm2CDkcgw26ioxTNQAZSrXg5J7QCVQvl2orpX4aCbVcwimMwgMj+fqYo43q8sYeLWCWVf7CPYpuyebwH1womgEsqxgNBdYX2asjiH64bJbWhUXS2QVnP8Q5djGQvH/gOuMPMgS/JGGUWy1k8XVjV5TsBV4GJknNU7VsScegik8Vso93C0y717GMeLmPZAkBACNoPdBpTH8SBzQXHIQoTA=
16 changes: 8 additions & 8 deletions calc/calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def check_parens(formula):
raise UnmatchedParenthesis(msg.format(count))


class ParseAugmenter(object):
class ParseAugmenter:
"""
Holds the data for a particular parse.
Expand Down Expand Up @@ -438,7 +438,7 @@ def handle_node(node):

node_name = node.getName()
if node_name not in handle_actions: # pragma: no cover
raise Exception(u"Unknown branch name '{}'".format(node_name))
raise Exception(f"Unknown branch name '{node_name}'")

action = handle_actions[node_name]
handled_kids = [handle_node(k) for k in node]
Expand All @@ -458,12 +458,12 @@ def check_variables(self, valid_variables, valid_functions):
else:
casify = lambda x: x.lower() # Lowercase for case insens.

bad_vars = set(var for var in self.variables_used
if casify(var) not in valid_variables)
bad_vars = {var for var in self.variables_used
if casify(var) not in valid_variables}

if bad_vars:
varnames = ", ".join(sorted(bad_vars))
message = "Invalid Input: {} not permitted in answer as a variable".format(varnames)
message = f"Invalid Input: {varnames} not permitted in answer as a variable"

# Check to see if there is a different case version of the variables
caselist = set()
Expand All @@ -478,11 +478,11 @@ def check_variables(self, valid_variables, valid_functions):

raise UndefinedVariable(message)

bad_funcs = set(func for func in self.functions_used
if casify(func) not in valid_functions)
bad_funcs = {func for func in self.functions_used
if casify(func) not in valid_functions}
if bad_funcs:
funcnames = ', '.join(sorted(bad_funcs))
message = "Invalid Input: {} not permitted in answer as a function".format(funcnames)
message = f"Invalid Input: {funcnames} not permitted in answer as a function"

# Check to see if there is a corresponding variable name
if any(casify(func) in valid_variables for func in bad_funcs):
Expand Down
44 changes: 22 additions & 22 deletions calc/preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from functools import reduce


class LatexRendered(object):
class LatexRendered:
"""
Data structure to hold a typeset representation of some math.
Expand Down Expand Up @@ -47,15 +47,15 @@ def __init__(self, latex, parens=None, tall=False):
r'\{': r'\}'}
if left_parens not in pairs:
raise Exception(
u"Unknown parenthesis '{}': coder error".format(left_parens)
f"Unknown parenthesis '{left_parens}': coder error"
)
right_parens = pairs[left_parens]

if self.tall:
left_parens = r"\left" + left_parens
right_parens = r"\right" + right_parens

self.latex = u"{left}{expr}{right}".format(
self.latex = "{left}{expr}{right}".format(
left=left_parens,
expr=latex,
right=right_parens
Expand All @@ -69,14 +69,14 @@ def __repr__(self): # pragma: no cover
If `tall` then have '<[]>' around the code, otherwise '<>'.
"""
if self.latex == self.sans_parens:
latex_repr = u'"{}"'.format(self.latex)
latex_repr = f'"{self.latex}"'
else:
latex_repr = u'"{}" or "{}"'.format(self.latex, self.sans_parens)
latex_repr = f'"{self.latex}" or "{self.sans_parens}"'

if self.tall:
wrap = u'<[{}]>'
wrap = '<[{}]>'
else:
wrap = u'<{}>'
wrap = '<{}>'

return wrap.format(latex_repr)

Expand All @@ -90,14 +90,14 @@ def render_number(children):
suffix = ""
if children_latex[-1] in SUFFIXES:
suffix = children_latex.pop()
suffix = u"\\text{{{s}}}".format(s=suffix)
suffix = f"\\text{{{suffix}}}"

# Exponential notation-- the "E" splits the mantissa and exponent
if "E" in children_latex:
pos = children_latex.index("E")
mantissa = "".join(children_latex[:pos])
exponent = "".join(children_latex[pos + 1:])
latex = u"{m}\\!\\times\\!10^{{{e}}}{s}".format(
latex = "{m}\\!\\times\\!10^{{{e}}}{s}".format(
m=mantissa, e=exponent, s=suffix
)
return LatexRendered(latex, tall=True)
Expand All @@ -124,7 +124,7 @@ def enrich_varname(varname):
greek.append('infty')

if varname in greek:
return u"\\{letter}".format(letter=varname)
return f"\\{varname}"
else:
return varname.replace("_", r"\_")

Expand All @@ -145,7 +145,7 @@ def render_variable(children):

if second:
# Then 'a_b' must become 'a_{b}'
varname = u"{a}_{{{b}}}".format(
varname = "{a}_{{{b}}}".format(
a=enrich_varname(first),
b=enrich_varname(second)
)
Expand Down Expand Up @@ -173,22 +173,22 @@ def render_function(children):
# Wrap the input of the function with parens or braces.
inner = children[1].latex
if fname == "sqrt":
inner = u"{{{expr}}}".format(expr=inner)
inner = f"{{{inner}}}"
else:
if children[1].tall:
inner = u"\\left({expr}\\right)".format(expr=inner)
inner = f"\\left({inner}\\right)"
else:
inner = u"({expr})".format(expr=inner)
inner = f"({inner})"

# Correctly format the name of the function.
if fname == "sqrt":
fname = u"\\sqrt"
fname = "\\sqrt"
elif fname == "log10":
fname = u"\\log_{10}"
fname = "\\log_{10}"
elif fname == "log2":
fname = u"\\log_2"
fname = "\\log_2"
else:
fname = u"\\text{{{fname}}}".format(fname=fname)
fname = f"\\text{{{fname}}}"

# Put it together.
latex = fname + inner
Expand All @@ -210,7 +210,7 @@ def render_power(children):
children_latex = [k.latex for k in children if k.latex != "^"]
children_latex[-1] = children[-1].sans_parens

raise_power = lambda x, y: u"{}^{{{}}}".format(y, x)
raise_power = lambda x, y: f"{y}^{{{x}}}"
latex = reduce(raise_power, reversed(children_latex))
return LatexRendered(latex, tall=True)

Expand Down Expand Up @@ -244,7 +244,7 @@ def render_frac(numerator, denominator):
else:
den_latex = r"\cdot ".join(k.latex for k in denominator)

latex = u"\\frac{{{num}}}{{{den}}}".format(num=num_latex, den=den_latex)
latex = f"\\frac{{{num_latex}}}{{{den_latex}}}"
return latex


Expand Down Expand Up @@ -348,8 +348,8 @@ def add_defaults(var, fun, case_sensitive=False):
fun_items.update(fun)

if not case_sensitive:
var_items = set(k.lower() for k in var_items)
fun_items = set(k.lower() for k in fun_items)
var_items = {k.lower() for k in var_items}
fun_items = {k.lower() for k in fun_items}

return var_items, fun_items

Expand Down
14 changes: 7 additions & 7 deletions calc/tests/test_calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ def test_exponential_answer(self):

for input_str in correct_responses:
result = calc.evaluator({}, {}, input_str)
fail_msg = "Expected '{0}' to equal {1}".format(
fail_msg = "Expected '{}' to equal {}".format(
input_str, answer
)
self.assertEqual(answer, result, msg=fail_msg)

for input_str in incorrect_responses:
result = calc.evaluator({}, {}, input_str)
fail_msg = "Expected '{0}' to not equal {1}".format(
fail_msg = "Expected '{}' to not equal {}".format(
input_str, answer
)
self.assertNotEqual(answer, result, msg=fail_msg)
Expand Down Expand Up @@ -113,9 +113,9 @@ def test_operator_sanity(self):
operators = [('+', 7), ('-', 3), ('*', 10), ('/', 2.5), ('^', 25)]

for (operator, answer) in operators:
input_str = "{0} {1} {2}".format(var1, operator, var2)
input_str = f"{var1} {operator} {var2}"
result = calc.evaluator({}, {}, input_str)
fail_msg = "Failed on operator '{0}': '{1}' was not {2}".format(
fail_msg = "Failed on operator '{}': '{}' was not {}".format(
operator, input_str, answer
)
self.assertEqual(answer, result, msg=fail_msg)
Expand Down Expand Up @@ -163,9 +163,9 @@ def assert_function_values(self, fname, ins, outs, tolerance=1e-3):
"""

for (arg, val) in zip(ins, outs):
input_str = "{0}({1})".format(fname, arg)
input_str = f"{fname}({arg})"
result = calc.evaluator({}, {}, input_str)
fail_msg = "Failed on function {0}: '{1}' was not {2}".format(
fail_msg = "Failed on function {}: '{}' was not {}".format(
fname, input_str, val
)
self.assertAlmostEqual(val, result, delta=tolerance, msg=fail_msg)
Expand Down Expand Up @@ -364,7 +364,7 @@ def test_constants(self):
('pi', 3.1416, 1e-4),
]
for (variable, value, tolerance) in default_variables:
fail_msg = "Failed on constant '{0}', not within bounds".format(
fail_msg = "Failed on constant '{}', not within bounds".format(
variable
)
result = calc.evaluator({}, {}, variable)
Expand Down
1 change: 0 additions & 1 deletion calc/tests/test_preview.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Unit tests for preview.py
"""
Expand Down
4 changes: 2 additions & 2 deletions requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@
#
# make upgrade
#
numpy==1.18.5 # via -r requirements/base.in, scipy
numpy==1.19.5 # via -r requirements/base.in, scipy
pyparsing==2.4.7 # via -r requirements/base.in
scipy==1.4.1 # via -r requirements/base.in
scipy==1.6.0 # via -r requirements/base.in
3 changes: 1 addition & 2 deletions requirements/pip_tools.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
# make upgrade
#
click==7.1.2 # via pip-tools
pip-tools==5.2.1 # via -r requirements/pip_tools.in
six==1.15.0 # via pip-tools
pip-tools==5.5.0 # via -r requirements/pip_tools.in

# The following packages are considered to be unsafe in a requirements file:
# pip
13 changes: 6 additions & 7 deletions requirements/test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@
# make upgrade
#
astroid==2.4.2 # via pylint
coverage==5.1 # via -r requirements/test.in
isort==4.3.21 # via pylint
coverage==5.3.1 # via -r requirements/test.in
isort==5.7.0 # via pylint
lazy-object-proxy==1.4.3 # via astroid
mccabe==0.6.1 # via pylint
numpy==1.18.5 # via -r requirements/base.txt, scipy
numpy==1.19.5 # via -r requirements/base.txt, scipy
pycodestyle==2.6.0 # via -r requirements/test.in
pylint==2.5.3 # via -r requirements/test.in
pylint==2.6.0 # via -r requirements/test.in
pyparsing==2.4.7 # via -r requirements/base.txt
scipy==1.4.1 # via -r requirements/base.txt
scipy==1.6.0 # via -r requirements/base.txt
six==1.15.0 # via astroid
toml==0.10.1 # via pylint
typed-ast==1.4.1 # via astroid
toml==0.10.2 # via pylint
wrapt==1.12.1 # via astroid
17 changes: 7 additions & 10 deletions requirements/tox.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,13 @@
# make upgrade
#
appdirs==1.4.4 # via virtualenv
distlib==0.3.0 # via virtualenv
distlib==0.3.1 # via virtualenv
filelock==3.0.12 # via tox, virtualenv
importlib-metadata==1.6.1 # via importlib-resources, pluggy, tox, virtualenv
importlib-resources==2.0.1 # via virtualenv
packaging==20.4 # via tox
packaging==20.8 # via tox
pluggy==0.13.1 # via tox
py==1.9.0 # via tox
py==1.10.0 # via tox
pyparsing==2.4.7 # via packaging
six==1.15.0 # via packaging, tox, virtualenv
toml==0.10.1 # via tox
tox==3.15.2 # via -r requirements/tox.in
virtualenv==20.0.25 # via tox
zipp==1.2.0 # via importlib-metadata, importlib-resources
six==1.15.0 # via tox, virtualenv
toml==0.10.2 # via tox
tox==3.21.0 # via -r requirements/tox.in
virtualenv==20.3.0 # via tox
31 changes: 14 additions & 17 deletions requirements/travis.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,21 @@
# make upgrade
#
appdirs==1.4.4 # via -r requirements/tox.txt, virtualenv
certifi==2020.6.20 # via requests
chardet==3.0.4 # via requests
coverage==5.1 # via coveralls
coveralls==2.0.0 # via -r requirements/travis.in
distlib==0.3.0 # via -r requirements/tox.txt, virtualenv
certifi==2020.12.5 # via requests
chardet==4.0.0 # via requests
coverage==5.3.1 # via coveralls
coveralls==3.0.0 # via -r requirements/travis.in
distlib==0.3.1 # via -r requirements/tox.txt, virtualenv
docopt==0.6.2 # via coveralls
filelock==3.0.12 # via -r requirements/tox.txt, tox, virtualenv
idna==2.9 # via requests
importlib-metadata==1.6.1 # via -r requirements/tox.txt, importlib-resources, pluggy, tox, virtualenv
importlib-resources==2.0.1 # via -r requirements/tox.txt, virtualenv
packaging==20.4 # via -r requirements/tox.txt, tox
idna==2.10 # via requests
packaging==20.8 # via -r requirements/tox.txt, tox
pluggy==0.13.1 # via -r requirements/tox.txt, tox
py==1.9.0 # via -r requirements/tox.txt, tox
py==1.10.0 # via -r requirements/tox.txt, tox
pyparsing==2.4.7 # via -r requirements/tox.txt, packaging
requests==2.24.0 # via coveralls
six==1.15.0 # via -r requirements/tox.txt, packaging, tox, virtualenv
toml==0.10.1 # via -r requirements/tox.txt, tox
tox==3.15.2 # via -r requirements/tox.txt
urllib3==1.25.9 # via requests
virtualenv==20.0.25 # via -r requirements/tox.txt, tox
zipp==1.2.0 # via -r requirements/tox.txt, importlib-metadata, importlib-resources
requests==2.25.1 # via coveralls
six==1.15.0 # via -r requirements/tox.txt, tox, virtualenv
toml==0.10.2 # via -r requirements/tox.txt, tox
tox==3.21.0 # via -r requirements/tox.txt
urllib3==1.26.2 # via requests
virtualenv==20.3.0 # via -r requirements/tox.txt, tox
Loading

0 comments on commit 193afec

Please sign in to comment.