Skip to content

Commit

Permalink
f-strings and other various syntax upgrades after dropping 3.7
Browse files Browse the repository at this point in the history
  • Loading branch information
mahmoud committed Nov 4, 2024
1 parent f0f9c2e commit 51421a3
Show file tree
Hide file tree
Showing 16 changed files with 102 additions and 121 deletions.
1 change: 0 additions & 1 deletion face/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from face.parser import (Flag,
FlagDisplay,
ERROR,
Expand Down
20 changes: 8 additions & 12 deletions face/command.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@

from __future__ import print_function

import sys
from collections import OrderedDict

Expand Down Expand Up @@ -97,7 +94,7 @@ def __init__(self, func, name=None, doc=None, **kwargs):
doc = _docstring_to_doc(func)

# TODO: default posargs if none by inspecting func
super(Command, self).__init__(name, doc,
super().__init__(name, doc,
flags=kwargs.pop('flags', None),
posargs=kwargs.pop('posargs', None),
post_posargs=kwargs.pop('post_posargs', None),
Expand All @@ -119,7 +116,7 @@ def __init__(self, func, name=None, doc=None, **kwargs):
self.add_middleware(mw)

if kwargs:
raise TypeError('unexpected keyword arguments: %r' % sorted(kwargs.keys()))
raise TypeError(f'unexpected keyword arguments: {sorted(kwargs.keys())!r}')

if _help:
if _help.flag:
Expand Down Expand Up @@ -178,7 +175,7 @@ def add(self, *a, **kw):
flag = a[0]
if not isinstance(flag, Flag):
flag = Flag(*a, **kw) # attempt to construct a Flag from arguments
super(Command, self).add(flag)
super().add(flag)

return flag

Expand All @@ -191,9 +188,9 @@ def add_command(self, subcmd):
conflicting middlewares or subcommand names.
"""
if not isinstance(subcmd, Command):
raise TypeError('expected Command instance, not: %r' % subcmd)
raise TypeError(f'expected Command instance, not: {subcmd!r}')
self_mw = self._path_mw_map[()]
super(Command, self).add(subcmd)
super().add(subcmd)
# map in new functions
for path in self.subprs_map:
if path not in self._path_func_map:
Expand Down Expand Up @@ -226,7 +223,7 @@ def get_flag_map(self, path=(), with_hidden=True):
the flag map to just the flags used by the endpoint at the
associated subcommand *path*.
"""
flag_map = super(Command, self).get_flag_map(path=path, with_hidden=with_hidden)
flag_map = super().get_flag_map(path=path, with_hidden=with_hidden)
dep_names = self.get_dep_names(path)
if 'args_' in dep_names or 'flags_' in dep_names:
# the argument parse result and flag dict both capture
Expand Down Expand Up @@ -315,7 +312,7 @@ def prepare(self, paths=None):
try:
wrapped = get_middleware_chain(mws, func, provides)
except NameError as ne:
ne.args = (ne.args[0] + ' (in path: %r)' % (path,),)
ne.args = (ne.args[0] + f' (in path: {path!r})',)
raise

self._path_wrapped_map[path] = wrapped
Expand Down Expand Up @@ -352,8 +349,7 @@ def run(self, argv=None, extras=None, print_error=None):
if print_error is None or print_error is True:
print_error = default_print_error
elif print_error and not callable(print_error):
raise TypeError('expected callable for print_error, not %r'
% print_error)
raise TypeError(f'expected callable for print_error, not {print_error!r}')

kwargs = dict(extras) if extras else {}
kwargs['print_error_'] = print_error # TODO: print_error_ in builtin provides?
Expand Down
16 changes: 6 additions & 10 deletions face/errors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

from boltons.iterutils import unique

import face.utils
Expand Down Expand Up @@ -50,8 +49,7 @@ def from_parse(cls, cmd_flag_map, flag_name):
# TODO: add edit distance calculation
valid_flags = unique([face.utils.format_flag_label(flag) for flag in
cmd_flag_map.values() if not flag.display.hidden])
msg = ('unknown flag "%s", choose from: %s'
% (flag_name, ', '.join(valid_flags)))
msg = f"unknown flag \"{flag_name}\", choose from: {', '.join(valid_flags)}"
return cls(msg)


Expand All @@ -63,7 +61,7 @@ class InvalidFlagArgument(ArgumentParseError):
@classmethod
def from_parse(cls, cmd_flag_map, flag, arg, exc=None):
if arg is None:
return cls('expected argument for flag %s' % flag.name)
return cls(f'expected argument for flag {flag.name}')

val_parser = flag.parse_as
vp_label = getattr(val_parser, 'display_name', face.utils.FRIENDLY_TYPE_NAMES.get(val_parser))
Expand All @@ -76,7 +74,7 @@ def from_parse(cls, cmd_flag_map, flag, arg, exc=None):

if exc:
# TODO: put this behind a verbose flag?
msg += ' (got error: %r)' % exc
msg += f' (got error: {exc!r})'
if arg.startswith('-'):
msg += '. (Did you forget to pass an argument?)'

Expand Down Expand Up @@ -105,8 +103,7 @@ def from_parse(cls, cmd_flag_map, parsed_flag_map, missing_flag_names):
for flag_name in flag_names:
flag = cmd_flag_map[flag_name]
labels.append(face.utils.format_flag_label(flag))
msg = ('missing required arguments for flags: %s'
% ', '.join(sorted(labels)))
msg = f"missing required arguments for flags: {', '.join(sorted(labels))}"
return cls(msg)


Expand All @@ -118,10 +115,9 @@ class DuplicateFlag(ArgumentParseError):
def from_parse(cls, flag, arg_val_list):
avl_text = ', '.join([repr(v) for v in arg_val_list])
if callable(flag.parse_as):
msg = ('more than one value was passed for flag "%s": %s'
% (flag.name, avl_text))
msg = f'more than one value was passed for flag "{flag.name}": {avl_text}'
else:
msg = ('flag "%s" was used multiple times, but can be used only once' % flag.name)
msg = f'flag "{flag.name}" was used multiple times, but can be used only once'
return cls(msg)


Expand Down
11 changes: 5 additions & 6 deletions face/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import os
import sys
import array
Expand Down Expand Up @@ -147,7 +146,7 @@ def get_stout_layout(labels, indent, sep, width=None, max_width=DEFAULT_MAX_WIDT
}


class StoutHelpFormatter(object):
class StoutHelpFormatter:
"""This formatter takes :class:`Parser` and :class:`Command` instances
and generates help text. The output style is inspired by, but not
the same as, argparse's automatic help formatting.
Expand Down Expand Up @@ -215,7 +214,7 @@ def __init__(self, **kwargs):
for key, val in self.default_context.items():
self.ctx[key] = kwargs.pop(key, val)
if kwargs:
raise TypeError('unexpected formatter arguments: %r' % list(kwargs.keys()))
raise TypeError(f'unexpected formatter arguments: {list(kwargs.keys())!r}')

def _get_layout(self, labels):
ctx = self.ctx
Expand Down Expand Up @@ -362,7 +361,7 @@ class AiryHelpFormatter(object):
'''


class HelpHandler(object):
class HelpHandler:
"""The HelpHandler is a one-stop object for that all-important CLI
feature: automatic help generation. It ties together the actual
help handler with the optional flag and subcommand such that it
Expand Down Expand Up @@ -402,11 +401,11 @@ def __init__(self, flag=DEFAULT_HELP_FLAG, subcmd=None,
self.subcmd = subcmd
self.func = func if func is not None else self.default_help_func
if not callable(self.func):
raise TypeError('expected help handler func to be callable, not %r' % func)
raise TypeError(f'expected help handler func to be callable, not {func!r}')

self.formatter = formatter
if not formatter:
raise TypeError('expected Formatter type or instance, not: %r' % formatter)
raise TypeError(f'expected Formatter type or instance, not: {formatter!r}')
if isinstance(formatter, type):
self.formatter = formatter(**formatter_kwargs)
elif formatter_kwargs:
Expand Down
10 changes: 5 additions & 5 deletions face/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,10 @@ def face_middleware(func=None, **kwargs):
if flags:
for flag in flags:
if not isinstance(flag, Flag):
raise TypeError('expected Flag object, not: %r' % flag)
raise TypeError(f'expected Flag object, not: {flag!r}')
optional = kwargs.pop('optional', False)
if kwargs:
raise TypeError('unexpected keyword arguments: %r' % kwargs.keys())
raise TypeError(f'unexpected keyword arguments: {kwargs.keys()!r}')

def decorate_face_middleware(func):
check_middleware(func, provides=provides)
Expand Down Expand Up @@ -239,13 +239,13 @@ def get_middleware_chain(middlewares, innermost, preprovided):
if INNER_NAME in get_arg_names(innermost):
raise NameError(_inner_exc_msg % (INNER_NAME, innermost))

mw_builtins = set(preprovided) - set([INNER_NAME])
mw_builtins = set(preprovided) - {INNER_NAME}
mw_provides = [list(mw._face_provides) for mw in middlewares]

mw_chain, mw_chain_args, mw_unres = make_chain(middlewares, mw_provides, innermost, mw_builtins, INNER_NAME)

if mw_unres:
msg = "unresolved middleware or handler arguments: %r" % sorted(mw_unres)
msg = f"unresolved middleware or handler arguments: {sorted(mw_unres)!r}"
avail_unres = mw_unres & (mw_builtins | set(sum(mw_provides, [])))
if avail_unres:
msg += (' (%r provided but not resolvable, check middleware order.)'
Expand All @@ -261,7 +261,7 @@ def check_middleware(func, provides=None):
raises :exc:`TypeError` if any issues are found.
"""
if not callable(func):
raise TypeError('expected middleware %r to be a function' % func)
raise TypeError(f'expected middleware {func!r} to be a function')
fb = get_fb(func)
# TODO: this currently gives __main__abc instead of __main__.abc
func_label = ''.join(get_callable_labels(func))
Expand Down
Loading

0 comments on commit 51421a3

Please sign in to comment.