Skip to content

Commit

Permalink
Use f-strings (#101)
Browse files Browse the repository at this point in the history
Wherever it makes sense to use them
  • Loading branch information
robertodr authored Aug 15, 2020
1 parent ec3e455 commit 60cdfcd
Show file tree
Hide file tree
Showing 9 changed files with 37 additions and 50 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

# -- Options for HTML output -------------------------------------------
html_title = "parselglossy Documentation"
html_short_title = "parselglossy {}".format(version)
html_short_title = f"parselglossy {version}"
html_show_sourcelink = False
html_sidebars = {
"**": ["logo-text.html", "globaltoc.html", "localtoc.html", "searchbox.html"]
Expand Down
44 changes: 16 additions & 28 deletions parselglossy/documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ def documentation_generator(
" Editing by hand is not recommended.\n"
)

header_fmt = (
"{comment:s}\n{markup:s}\n{header:s}\n{markup:s}\n\n"
header = (
f"{comment:s}\n{'=' * len(header):s}\n{header:s}\n{'=' * len(header):s}\n\n"
"- Keywords without a default value are **required**.\n"
"- Default values are either explicit or computed from the value of other keywords in the input.\n" # noqa: E501
"- Sections where all keywords have a default value can be omitted.\n"
Expand All @@ -68,40 +68,30 @@ def documentation_generator(

docs = _rec_documentation_generator(template=template)

documentation = (
header_fmt.format(comment=comment, markup=("=" * len(header)), header=header)
+ docs
)
documentation = header + docs

return documentation


def _document_keyword(keyword: JSONDict) -> str:
kw_fmt = """
:{0:s}: {1:s}
docstring = keyword["docstring"].replace("\n", " ")
doc = f"""
:{keyword['name']:s}: {docstring:s}
**Type** ``{2:s}``
**Type** ``{keyword['type']:s}``
"""

doc = kw_fmt.format(
keyword["name"], keyword["docstring"].replace("\n", " "), keyword["type"]
)

if "default" in keyword.keys():
doc += """
**Default** ``{}``
""".format(
keyword["default"]
)
doc += f"""
**Default** ``{keyword['default']}``
"""

if "predicates" in keyword.keys():
preds = "\n ".join(("- ``{}``".format(x) for x in keyword["predicates"]))
doc += """
preds = "\n ".join((f"- ``{x}``" for x in keyword["predicates"]))
doc += f"""
**Predicates**
{}
""".format(
preds
)
{preds}
"""

return doc

Expand Down Expand Up @@ -132,11 +122,9 @@ def _rec_documentation_generator(template, *, level: int = 0) -> str:
sections = template["sections"] if "sections" in template.keys() else []
if sections:
docs.append(_indent("\n:red:`Sections`", level))
fmt = r"""
:{0:s}: {1:s}
"""
for s in sections:
doc = fmt.format(s["name"], s["docstring"].replace("\n", " "))
docstring = s["docstring"].replace("\n", " ")
doc = f"\n :{s['name']:s}: {docstring:s}\n"
doc += _rec_documentation_generator(s, level=level + 1)
docs.extend(_indent(doc, level))

Expand Down
11 changes: 5 additions & 6 deletions parselglossy/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ def __eq__(self, other):
return self.address == other.address and self.message == other.message

def __repr__(self):
msg = "{:s}".format(self.message)
msg = f"{self.message:s}"
if self.address != ():
msg = "At {:s}:\n {:s}".format(location_in_dict(address=self.address), msg)
msg = f"At {location_in_dict(address=self.address):s}:\n {msg:s}"
return "- " + msg


Expand All @@ -93,9 +93,8 @@ def collate_errors(*, when: str, errors: List[Error]) -> str:
KeyError 'min_num_iterations' in closure
'user['scf']['min_num_iterations'] / 2'
"""
preamble = "\nError{more:s} occurred when {when:s}:".format(
more="s" if len(errors) > 1 else "", when=when
)
msgs = [preamble] + ["{}".format(e) for e in errors]
plural = "s" if len(errors) > 1 else ""
preamble = f"\nError{plural:s} occurred when {when:s}:"
msgs = [preamble] + [f"{e}" for e in errors]

return "\n".join(msgs)
4 changes: 2 additions & 2 deletions parselglossy/grammars/lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def lex_from_str(
*,
in_str: Union[str, Path],
grammar: str = "standard",
ir_file: Optional[Union[str, Path]] = None
ir_file: Optional[Union[str, Path]] = None,
) -> JSONDict:
"""Run grammar of choice on input string.
Expand All @@ -100,7 +100,7 @@ def lex_from_str(
try:
lexer = dispatch_grammar(grammar)
except KeyError:
raise ParselglossyError("Grammar {} not available.".format(grammar))
raise ParselglossyError(f"Grammar {grammar} not available.")

ir = parse_string_to_dict(lexer, in_str)

Expand Down
4 changes: 2 additions & 2 deletions parselglossy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

ListTypes = Union[List[bool], List[str], List[int], List[float], List[complex]]

allowed_list_types = ["List[{}]".format(t) for t in allowed_scalar_types]
allowed_list_types = [f"List[{t}]" for t in allowed_scalar_types]

AllowedTypes = Union[ScalarTypes, ListTypes]

Expand Down Expand Up @@ -85,7 +85,7 @@ def type_matches(value: AllowedTypes, expected_type: str) -> Optional[bool]:

# first verify whether expected_type is allowed
if expected_type not in allowed_types:
raise ValueError("could not recognize expected_type: {}".format(expected_type))
raise ValueError(f"could not recognize expected_type: {expected_type}")

expected_complex = expected_type == "complex" or expected_type == "List[complex]"

Expand Down
8 changes: 4 additions & 4 deletions parselglossy/validation_plumbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,16 +492,16 @@ def run_callable(f: str, d: JSONDict, *, t: str) -> Tuple[str, Optional[Any]]:
result = eval(f"lambda user: {f}")(d)
result = type_fixers[t](result)
except KeyError as e:
msg = f"KeyError {e} in closure '{f}'"
msg = f"KeyError {e} in closure '{f}'."
result = None
except SyntaxError as e:
msg = f"SyntaxError {e} in closure '{f}'"
msg = f"SyntaxError {e} in closure '{f}'."
result = None
except TypeError as e:
msg = f"TypeError {e} in closure '{f}'"
msg = f"TypeError {e} in closure '{f}'."
result = None
except NameError as e:
msg = f"NameError {e} in closure '{f}'"
msg = f"NameError {e} in closure '{f}'."
result = None

return msg, result
Expand Down
4 changes: 2 additions & 2 deletions parselglossy/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def view_by(
*,
predicate: Callable[[Any, str], bool] = lambda x, y: True,
missing: Optional[Type[Exception]] = None,
transformer: Callable[[Any], Any] = lambda x: x
transformer: Callable[[Any], Any] = lambda x: x,
) -> JSONDict:
"""Recursive decimation of a template into an input.
Expand Down Expand Up @@ -159,7 +159,7 @@ def view_by(
allowed = ["type", "default", "docstring", "predicates"]
if what not in allowed:
raise ValueError(
"Requested view {:s} not among possible views ({})".format(what, allowed)
f"Requested view {what:s} not among possible views ({allowed})"
)

# Determine whether we have only sections and only keywords
Expand Down
8 changes: 4 additions & 4 deletions tests/test_atoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@

@given(a=st.sampled_from(atoms.TRUTHY + atoms.FALSEY))
def test_atom_bool(a):
tokens = atoms.bool_t.parseString("{:s}".format(a)).asList()
tokens = atoms.bool_t.parseString(f"{a:s}").asList()
assert tokens[0] == atoms.to_bool(a)


@given(a=st.integers())
def test_atoms_int(a):
tokens = atoms.int_t.parseString("{:d}".format(a)).asList()
tokens = atoms.int_t.parseString(f"{a:d}").asList()
assert tokens[0] == a


Expand Down Expand Up @@ -118,12 +118,12 @@ def test_atoms_data(a):
@pytest.mark.parametrize("a", ["[]", "[ ]", "[\n]"])
def test_list_empty(a):
with pytest.raises(ParseBaseException, match=r"^Empty lists not allowed"):
tokens = atoms.list_t.parseString("{}".format(a)).asList()
_ = atoms.list_t.parseString(f"{a}").asList()


@given(a=st.lists(st.integers(), min_size=1))
def test_list_int(a):
tokens = atoms.list_t.parseString("{}".format(a)).asList()
tokens = atoms.list_t.parseString(f"{a}").asList()
assert tokens == a


Expand Down
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
"switch,expected",
[
([], "Console script for parselglossy"),
(["--version"], "parselglossy, version {}".format(__version__)),
(["--version"], f"parselglossy, version {__version__}"),
(["--help"], r"--help\s+Show this message and exit"),
],
ids=["plain", "version", "help"],
Expand Down

0 comments on commit 60cdfcd

Please sign in to comment.