diff --git a/docs/conf.py b/docs/conf.py index 45953ec..a431ebd 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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"] diff --git a/parselglossy/documentation.py b/parselglossy/documentation.py index 0c1a9ba..7a0b669 100644 --- a/parselglossy/documentation.py +++ b/parselglossy/documentation.py @@ -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" @@ -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 @@ -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)) diff --git a/parselglossy/exceptions.py b/parselglossy/exceptions.py index 5d881ca..cec3e81 100644 --- a/parselglossy/exceptions.py +++ b/parselglossy/exceptions.py @@ -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 @@ -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) diff --git a/parselglossy/grammars/lexer.py b/parselglossy/grammars/lexer.py index 3b810b9..59a7f8f 100644 --- a/parselglossy/grammars/lexer.py +++ b/parselglossy/grammars/lexer.py @@ -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. @@ -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) diff --git a/parselglossy/types.py b/parselglossy/types.py index 9ec1feb..a346eec 100644 --- a/parselglossy/types.py +++ b/parselglossy/types.py @@ -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] @@ -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]" diff --git a/parselglossy/validation_plumbing.py b/parselglossy/validation_plumbing.py index 38b6eee..3b91def 100644 --- a/parselglossy/validation_plumbing.py +++ b/parselglossy/validation_plumbing.py @@ -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 diff --git a/parselglossy/views.py b/parselglossy/views.py index 3e8c5f9..f85f805 100644 --- a/parselglossy/views.py +++ b/parselglossy/views.py @@ -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. @@ -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 diff --git a/tests/test_atoms.py b/tests/test_atoms.py index a765b6d..720dada 100644 --- a/tests/test_atoms.py +++ b/tests/test_atoms.py @@ -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 @@ -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 diff --git a/tests/test_cli.py b/tests/test_cli.py index 89a1235..b1e77c3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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"],