Skip to content

Commit

Permalink
Use f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Jan 30, 2024
1 parent f64d4f8 commit 66845c3
Show file tree
Hide file tree
Showing 9 changed files with 74 additions and 75 deletions.
8 changes: 4 additions & 4 deletions glom/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def glom_cli(target, spec, indent, debug, inspect):
try:
result = glom.glom(target, spec)
except GlomError as ge:
print('{}: {}'.format(ge.__class__.__name__, ge))
print(f'{ge.__class__.__name__}: {ge}')
return 1

if not indent:
Expand Down Expand Up @@ -172,7 +172,7 @@ def mw_get_target(next_, posargs_, target_file, target_format, spec_file, spec_f
with open(spec_file) as f:
spec_text = f.read()
except OSError as ose:
raise UsageError('could not read spec file {!r}, got: {}'.format(spec_file, ose))
raise UsageError(f'could not read spec file {spec_file!r}, got: {ose}')

if not spec_text:
spec = Path()
Expand All @@ -196,7 +196,7 @@ def mw_get_target(next_, posargs_, target_file, target_format, spec_file, spec_f
try:
target_text = open(target_file).read()
except OSError as ose:
raise UsageError('could not read target file {!r}, got: {}'.format(target_file, ose))
raise UsageError(f'could not read target file {target_file!r}, got: {ose}')
elif not target_text and not isatty(sys.stdin):
target_text = sys.stdin.read()

Expand All @@ -217,7 +217,7 @@ def _from_glom_import_star():

def _eval_python_full_spec(py_text):
name = '__cli_glom_spec__'
code_str = '{} = {}'.format(name, py_text)
code_str = f'{name} = {py_text}'
env = _from_glom_import_star()
spec = _compile_code(code_str, name=name, env=env)
return spec
Expand Down
58 changes: 29 additions & 29 deletions glom/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ def _format_trace_value(value, maxlen):
s = bbrepr(value).replace("\\'", "'")
if len(s) > maxlen:
try:
suffix = '... (len=%s)' % len(value)
suffix = f'... (len={len(value)})'
except Exception:
suffix = '...'
s = s[:maxlen - len(suffix)] + suffix
Expand Down Expand Up @@ -351,7 +351,7 @@ def get_message(self):

def __repr__(self):
cn = self.__class__.__name__
return '{}({!r}, {!r}, {!r})'.format(cn, self.exc, self.path, self.part_idx)
return f'{cn}({self.exc!r}, {self.path!r}, {self.part_idx!r})'


class PathAssignError(GlomError):
Expand Down Expand Up @@ -381,7 +381,7 @@ def get_message(self):

def __repr__(self):
cn = self.__class__.__name__
return '{}({!r}, {!r}, {!r})'.format(cn, self.exc, self.path, self.dest_name)
return f'{cn}({self.exc!r}, {self.path!r}, {self.dest_name!r})'


class CoalesceError(GlomError):
Expand Down Expand Up @@ -422,22 +422,22 @@ def __init__(self, coal_obj, skipped, path):

def __repr__(self):
cn = self.__class__.__name__
return '{}({!r}, {!r}, {!r})'.format(cn, self.coal_obj, self.skipped, self.path)
return f'{cn}({self.coal_obj!r}, {self.skipped!r}, {self.path!r})'

def get_message(self):
missed_specs = tuple(self.coal_obj.subspecs)
skipped_vals = [v.__class__.__name__
if isinstance(v, self.coal_obj.skip_exc)
else '<skipped %s>' % v.__class__.__name__
else f'<skipped {v.__class__.__name__}>'
for v in self.skipped]
msg = ('no valid values found. Tried %r and got (%s)'
% (missed_specs, ', '.join(skipped_vals)))
if self.coal_obj.skip is not _MISSING:
msg += ', skip set to {!r}'.format(self.coal_obj.skip)
msg += f', skip set to {self.coal_obj.skip!r}'

Check warning on line 436 in glom/core.py

View check run for this annotation

Codecov / codecov/patch

glom/core.py#L436

Added line #L436 was not covered by tests
if self.coal_obj.skip_exc is not GlomError:
msg += ', skip_exc set to {!r}'.format(self.coal_obj.skip_exc)
msg += f', skip_exc set to {self.coal_obj.skip_exc!r}'

Check warning on line 438 in glom/core.py

View check run for this annotation

Codecov / codecov/patch

glom/core.py#L438

Added line #L438 was not covered by tests
if self.path is not None:
msg += ' (at path {!r})'.format(self.path)
msg += f' (at path {self.path!r})'
return msg


Expand Down Expand Up @@ -488,11 +488,11 @@ def get_message(self):
return ("glom() called without registering any types for operation '%s'. see"
" glom.register() or Glommer's constructor for details." % (self.op,))
reg_types = sorted([t.__name__ for t, h in self.type_map.items() if h])
reg_types_str = '()' if not reg_types else ('(%s)' % ', '.join(reg_types))
reg_types_str = '()' if not reg_types else (f"({', '.join(reg_types)})")
msg = ("target type %r not registered for '%s', expected one of"
" registered types: %s" % (self.target_type.__name__, self.op, reg_types_str))
if self.path:
msg += ' (at {!r})'.format(self.path)
msg += f' (at {self.path!r})'
return msg


Expand Down Expand Up @@ -557,21 +557,21 @@ def format_invocation(name='', args=(), kwargs=None, **kw):
"""
_repr = kw.pop('repr', bbrepr)
if kw:
raise TypeError('unexpected keyword args: %r' % ', '.join(kw.keys()))
raise TypeError(f"unexpected keyword args: {', '.join(kw.keys())!r}")

Check warning on line 560 in glom/core.py

View check run for this annotation

Codecov / codecov/patch

glom/core.py#L560

Added line #L560 was not covered by tests
kwargs = kwargs or {}
a_text = ', '.join([_repr(a) for a in args])
if isinstance(kwargs, dict):
kwarg_items = [(k, kwargs[k]) for k in sorted(kwargs)]
else:
kwarg_items = kwargs
kw_text = ', '.join(['{}={}'.format(k, _repr(v)) for k, v in kwarg_items])
kw_text = ', '.join([f'{k}={_repr(v)}' for k, v in kwarg_items])

all_args_text = a_text
if all_args_text and kw_text:
all_args_text += ', '
all_args_text += kw_text

return '{}({})'.format(name, all_args_text)
return f'{name}({all_args_text})'


class Path:
Expand Down Expand Up @@ -819,8 +819,8 @@ def glomit(self, target, scope):
def __repr__(self):
cn = self.__class__.__name__
if self.scope:
return '{}({}, scope={!r})'.format(cn, bbrepr(self.spec), self.scope)
return '{}({})'.format(cn, bbrepr(self.spec))
return f'{cn}({bbrepr(self.spec)}, scope={self.scope!r})'
return f'{cn}({bbrepr(self.spec)})'


class Coalesce:
Expand Down Expand Up @@ -914,7 +914,7 @@ def __init__(self, *subspecs, **kwargs):
self.skip_func = lambda v: v == self.skip
self.skip_exc = kwargs.pop('skip_exc', GlomError)
if kwargs:
raise TypeError('unexpected keyword args: {!r}'.format(sorted(kwargs.keys())))
raise TypeError(f'unexpected keyword args: {sorted(kwargs.keys())!r}')

def glomit(self, target, scope):
skipped = []
Expand Down Expand Up @@ -996,13 +996,13 @@ def __init__(self, *a, **kw):
if breakpoint is True:
breakpoint = pdb.set_trace
if breakpoint and not callable(breakpoint):
raise TypeError('breakpoint expected bool or callable, not: %r' % breakpoint)
raise TypeError(f'breakpoint expected bool or callable, not: {breakpoint!r}')
self.breakpoint = breakpoint
post_mortem = kw.pop('post_mortem', False)
if post_mortem is True:
post_mortem = pdb.post_mortem
if post_mortem and not callable(post_mortem):
raise TypeError('post_mortem expected bool or callable, not: %r' % post_mortem)
raise TypeError(f'post_mortem expected bool or callable, not: {post_mortem!r}')
self.post_mortem = post_mortem

def __repr__(self):
Expand Down Expand Up @@ -1096,7 +1096,7 @@ def glomit(self, target, scope):

def __repr__(self):
cn = self.__class__.__name__
return '{}({}, args={!r}, kwargs={!r})'.format(cn, bbrepr(self.func), self.args, self.kwargs)
return f'{cn}({bbrepr(self.func)}, args={self.args!r}, kwargs={self.kwargs!r})'


def _is_spec(obj, strict=False):
Expand Down Expand Up @@ -1439,7 +1439,7 @@ def __getitem__(self, item):
def __call__(self, *args, **kwargs):
if self is S:
if args:
raise TypeError('S() takes no positional arguments, got: {!r}'.format(args))
raise TypeError(f'S() takes no positional arguments, got: {args!r}')
if not kwargs:
raise TypeError('S() expected at least one kwarg, got none')
# TODO: typecheck kwarg vals?
Expand Down Expand Up @@ -1733,7 +1733,7 @@ def _format_t(path, root=T):
index = ", ".join([_format_slice(x) for x in arg])
else:
index = _format_slice(arg)
prepr.append("[{}]".format(index))
prepr.append(f"[{index}]")
elif op == '(':
args, kwargs = arg
prepr.append(format_invocation(args=args, kwargs=kwargs, repr=bbrepr))
Expand Down Expand Up @@ -1788,7 +1788,7 @@ def glomit(self, target, scope):

def __repr__(self):
cn = self.__class__.__name__
return '{}({})'.format(cn, bbrepr(self.value))
return f'{cn}({bbrepr(self.value)})'


Literal = Val # backwards compat for pre-20.7.0
Expand All @@ -1812,7 +1812,7 @@ def __iter__(self):
return iter(self.__dict__.items())

def __repr__(self):
return "{}({})".format(self.__class__.__name__, bbrepr(self.__dict__))
return f"{self.__class__.__name__}({bbrepr(self.__dict__)})"


class Vars:
Expand Down Expand Up @@ -1885,7 +1885,7 @@ def glomit(self, target, scope):
def __repr__(self):
cn = self.__class__.__name__
rpr = '' if self.spec is None else bbrepr(self.spec)
return '{}({})'.format(cn, rpr)
return f'{cn}({rpr})'


class _AbstractIterable(_AbstractIterableBase):
Expand Down Expand Up @@ -2093,7 +2093,7 @@ def _register_fuzzy_type(self, op, new_type, _type_tree=None):

def register(self, target_type, **kwargs):
if not isinstance(target_type, type):
raise TypeError('register expected a type, not an instance: {!r}'.format(target_type))
raise TypeError(f'register expected a type, not an instance: {target_type!r}')
exact = kwargs.pop('exact', None)
new_op_map = dict(kwargs)

Expand Down Expand Up @@ -2139,11 +2139,11 @@ def register_op(self, op_name, auto_func=None, exact=False):
extensions.
"""
if not isinstance(op_name, basestring):
raise TypeError('expected op_name to be a text name, not: {!r}'.format(op_name))
raise TypeError(f'expected op_name to be a text name, not: {op_name!r}')
if auto_func is None:
auto_func = lambda t: False
elif not callable(auto_func):
raise TypeError('expected auto_func to be callable, not: {!r}'.format(auto_func))
raise TypeError(f'expected auto_func to be callable, not: {auto_func!r}')

# determine support for any previously known types
known_types = set(sum([list(m.keys()) for m
Expand Down Expand Up @@ -2268,7 +2268,7 @@ def glom(target, spec, **kwargs):
scope.update(kwargs.pop('scope', {}))
err = None
if kwargs:
raise TypeError('unexpected keyword args: %r' % sorted(kwargs.keys()))
raise TypeError(f'unexpected keyword args: {sorted(kwargs.keys())!r}')
try:
try:
ret = _glom(target, spec, scope)
Expand Down Expand Up @@ -2537,7 +2537,7 @@ def fill(self, target):
def __repr__(self):
cn = self.__class__.__name__
rpr = '' if self.spec is None else bbrepr(self.spec)
return '{}({})'.format(cn, rpr)
return f'{cn}({rpr})'


def FILL(target, spec, scope):
Expand Down
14 changes: 7 additions & 7 deletions glom/grouping.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def glomit(self, target, scope):

def __repr__(self):
cn = self.__class__.__name__
return '{}({!r})'.format(cn, self.spec)
return f'{cn}({self.spec!r})'


def GROUP(target, spec, scope):
Expand Down Expand Up @@ -171,7 +171,7 @@ def agg(self, target, tree):
return STOP

def __repr__(self):
return '%s()' % self.__class__.__name__
return f'{self.__class__.__name__}()'


class Avg:
Expand All @@ -195,7 +195,7 @@ def agg(self, target, tree):
return avg_acc[0] / avg_acc[1]

def __repr__(self):
return '%s()' % self.__class__.__name__
return f'{self.__class__.__name__}()'


class Max:
Expand All @@ -214,7 +214,7 @@ def agg(self, target, tree):
return tree[self]

def __repr__(self):
return '%s()' % self.__class__.__name__
return f'{self.__class__.__name__}()'


class Min:
Expand All @@ -233,7 +233,7 @@ def agg(self, target, tree):
return tree[self]

def __repr__(self):
return '%s()' % self.__class__.__name__
return f'{self.__class__.__name__}()'


class Sample:
Expand Down Expand Up @@ -270,7 +270,7 @@ def agg(self, target, tree):
return sample

def __repr__(self):
return '{}({!r})'.format(self.__class__.__name__, self.size)
return f'{self.__class__.__name__}({self.size!r})'



Expand Down Expand Up @@ -313,4 +313,4 @@ def glomit(self, target, scope):
return scope[glom](target, self.subspec, scope)

def __repr__(self):
return '{}({!r}, {!r})'.format(self.__class__.__name__, self.n, self.subspec)
return f'{self.__class__.__name__}({self.n!r}, {self.subspec!r})'
Loading

0 comments on commit 66845c3

Please sign in to comment.