Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

STY: fixes Pylint C0209 Errors (uses f-strings) #26279

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/benchmarks/bench_records.py
Expand Up @@ -12,7 +12,7 @@ def setup(self):
self.formats_str = ','.join(self.formats)
self.dtype_ = np.dtype(
[
('field_{}'.format(i), self.l50.dtype.str)
(f'field_{i}', self.l50.dtype.str)
for i in range(self.fields_number)
]
)
Expand Down
7 changes: 4 additions & 3 deletions benchmarks/benchmarks/bench_ufunc.py
Expand Up @@ -506,10 +506,11 @@ def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __repr__(self):
return '({})'.format(', '.join(
joined_elements = ', '.join(
[repr(a) for a in self.args] +
['{}={}'.format(k, repr(v)) for k, v in self.kwargs.items()]
))
[f'{k}={repr(v)}' for k, v in self.kwargs.items()]
)
return f'({joined_elements})'


class ArgParsing(Benchmark):
Expand Down
2 changes: 1 addition & 1 deletion doc/neps/nep-0013-ufunc-overrides.rst
Expand Up @@ -526,7 +526,7 @@ multiplication::
def __init__(self, value):
self.value = value
def __repr__(self):
return "MyObject({!r})".format(self.value)
return f"MyObject({self.value!r})"
def __mul__(self, other):
return MyObject(1234)
def __rmul__(self, other):
Expand Down
2 changes: 1 addition & 1 deletion doc/source/reference/random/bit_generators/index.rst
Expand Up @@ -91,7 +91,7 @@ user, which is up to you.
# If the user did not provide a seed, it should return `None`.
seed = get_user_seed()
ss = SeedSequence(seed)
print('seed = {}'.format(ss.entropy))
print(f'seed = {ss.entropy}')
bg = PCG64(ss)

.. end_block
Expand Down
6 changes: 3 additions & 3 deletions numpy/__init__.py
Expand Up @@ -407,8 +407,8 @@ def __getattr__(attr):
import numpy.char as char
return char.chararray

raise AttributeError("module {!r} has no attribute "
"{!r}".format(__name__, attr))
raise AttributeError(f"module {__name__!r} has no attribute "
f"{attr!r}")

def __dir__():
public_symbols = (
Expand Down Expand Up @@ -480,7 +480,7 @@ def _mac_os_check():
"\nIf you compiled yourself, more information is available at:"
"\nhttps://numpy.org/devdocs/building/index.html"
"\nOtherwise report this to the vendor "
"that provided NumPy.\n\n{}\n".format(error_message))
f"that provided NumPy.\n\n{error_message}\n")
raise RuntimeError(msg)
del _wn
del w
Expand Down
24 changes: 9 additions & 15 deletions numpy/_core/_dtype.py
Expand Up @@ -46,7 +46,7 @@ def __repr__(dtype):
arg_str = _construction_repr(dtype, include_align=False)
if dtype.isalignedstruct:
arg_str = arg_str + ", align=True"
return "dtype({})".format(arg_str)
return f"dtype({arg_str})"


def _unpack_field(dtype, offset, title=None):
Expand Down Expand Up @@ -187,9 +187,9 @@ def _datetime_metadata_str(dtype):
if unit == 'generic':
return ''
elif count == 1:
return '[{}]'.format(unit)
return f'[{unit}]'
else:
return '[{}{}]'.format(count, unit)
return f'[{count}{unit}]'


def _struct_dict_str(dtype, includealignedflag):
Expand Down Expand Up @@ -289,16 +289,13 @@ def _struct_list_str(dtype):

item = "("
if title is not None:
item += "({!r}, {!r}), ".format(title, name)
item += f"({title!r}, {name!r}), "
else:
item += "{!r}, ".format(name)
item += f"{name!r}, "
# Special case subarray handling here
if fld_dtype.subdtype is not None:
base, shape = fld_dtype.subdtype
item += "{}, {}".format(
_construction_repr(base, short=True),
shape
)
item += f"{_construction_repr(base, short=True)}, {shape}"
else:
item += _construction_repr(fld_dtype, short=True)

Expand All @@ -320,17 +317,14 @@ def _struct_str(dtype, include_align):

# If the data type isn't the default, void, show it
if dtype.type != np.void:
return "({t.__module__}.{t.__name__}, {f})".format(t=dtype.type, f=sub)
return f"({dtype.type.__module__}.{dtype.type.__name__}, {sub})"
else:
return sub


def _subarray_str(dtype):
base, shape = dtype.subdtype
return "({}, {})".format(
_construction_repr(base, short=True),
shape
)
return f"({_construction_repr(base, short=True)}, {shape})"


def _name_includes_bit_suffix(dtype):
Expand Down Expand Up @@ -367,7 +361,7 @@ def _name_get(dtype):

# append bit counts
if _name_includes_bit_suffix(dtype):
name += "{}".format(dtype.itemsize * 8)
name += f"{dtype.itemsize * 8}"

# append metadata to datetimes
if dtype.type in (np.datetime64, np.timedelta64):
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/_dtype_ctypes.py
Expand Up @@ -117,4 +117,4 @@ def dtype_from_ctypes_type(t):
return _from_ctypes_scalar(t)
else:
raise NotImplementedError(
"Unknown ctypes type {}".format(t.__name__))
f"Unknown ctypes type {t.__name__}")
26 changes: 11 additions & 15 deletions numpy/_core/_exceptions.py
Expand Up @@ -86,12 +86,10 @@ def __init__(self, ufunc, casting, from_, to, i):

def __str__(self):
# only show the number if more than one input exists
i_str = "{} ".format(self.in_i) if self.ufunc.nin != 1 else ""
i_str = f"{self.in_i} " if self.ufunc.nin != 1 else ""
return (
"Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting "
"rule {!r}"
).format(
self.ufunc.__name__, i_str, self.from_, self.to, self.casting
f"Cannot cast ufunc {self.ufunc.__name__!r} input {i_str}from "
f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
)


Expand All @@ -104,12 +102,10 @@ def __init__(self, ufunc, casting, from_, to, i):

def __str__(self):
# only show the number if more than one output exists
i_str = "{} ".format(self.out_i) if self.ufunc.nout != 1 else ""
i_str = f"{self.out_i} " if self.ufunc.nout != 1 else ""
return (
"Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting "
"rule {!r}"
).format(
self.ufunc.__name__, i_str, self.from_, self.to, self.casting
f"Cannot cast ufunc {self.ufunc.__name__!r} output {i_str}from "
f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
)


Expand Down Expand Up @@ -156,17 +152,17 @@ def _size_to_string(num_bytes):
# format with a sensible number of digits
if unit_i == 0:
# no decimal point on bytes
return '{:.0f} {}'.format(n_units, unit_name)
return f'{n_units:.0f} {unit_name}'
elif round(n_units) < 1000:
# 3 significant figures, if none are dropped to the left of the .
return '{:#.3g} {}'.format(n_units, unit_name)
return f'{n_units:#.3g} {unit_name}'
else:
# just give all the digits otherwise
return '{:#.0f} {}'.format(n_units, unit_name)
return f'{n_units:#.0f} {unit_name}'

def __str__(self):
size_str = self._size_to_string(self._total_size)
return (
"Unable to allocate {} for an array with shape {} and data type {}"
.format(size_str, self.shape, self.dtype)
f"Unable to allocate {size_str} for an array with "
f"shape {self.shape} and data type {self.dtype}"
)
33 changes: 13 additions & 20 deletions numpy/_core/_internal.py
Expand Up @@ -869,21 +869,21 @@ def _lcm(a, b):

def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
""" Format the error message for when __array_ufunc__ gives up. """
args_string = ', '.join(['{!r}'.format(arg) for arg in inputs] +
['{}={!r}'.format(k, v)
for k, v in kwargs.items()])
args_string = ', '.join(
[f"{arg!r}" for arg in inputs] +
[f"{k}={v!r}" for k, v in kwargs.items()])
args = inputs + kwargs.get('out', ())
types_string = ', '.join(repr(type(arg).__name__) for arg in args)
return ('operand type(s) all returned NotImplemented from '
'__array_ufunc__({!r}, {!r}, {}): {}'
.format(ufunc, method, args_string, types_string))
return (
'operand type(s) all returned NotImplemented from __array_ufunc__'
f'({ufunc!r}, {method!r}, {args_string}): {types_string}')


def array_function_errmsg_formatter(public_api, types):
""" Format the error message for when __array_ufunc__ gives up. """
func_name = '{}.{}'.format(public_api.__module__, public_api.__name__)
return ("no implementation found for '{}' on types that implement "
'__array_function__: {}'.format(func_name, list(types)))
func_name = f'{public_api.__module__}.{public_api.__name__}'
return (f"no implementation found for '{func_name}' on types "
f"that implement __array_function__: {list(types)}")


def _ufunc_doc_signature_formatter(ufunc):
Expand All @@ -905,11 +905,9 @@ def _ufunc_doc_signature_formatter(ufunc):
elif ufunc.nout == 1:
out_args = ', /, out=None'
else:
out_args = '[, {positional}], / [, out={default}]'.format(
positional=', '.join(
'out{}'.format(i+1) for i in range(ufunc.nout)),
default=repr((None,)*ufunc.nout)
)
positional = ', '.join(
f'out{i+1}' for i in range(ufunc.nout))
out_args = f'[, {positional}], / [, out={repr((None,)*ufunc.nout)}]'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: binding a default variable as well would be more readable IMO

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, good point. I'll look into making it more readable.


# keyword only args depend on whether this is a gufunc
kwargs = (
Expand All @@ -926,12 +924,7 @@ def _ufunc_doc_signature_formatter(ufunc):
kwargs += "[, signature, axes, axis]"

# join all the parts together
return '{name}({in_args}{out_args}, *{kwargs})'.format(
name=ufunc.__name__,
in_args=in_args,
out_args=out_args,
kwargs=kwargs
)
return f'{ufunc.__name__}({in_args}{out_args}, *{kwargs})'


def npy_ctypes_check(cls):
Expand Down
13 changes: 7 additions & 6 deletions numpy/_core/arrayprint.py
Expand Up @@ -77,7 +77,7 @@ def _make_options_dict(precision=None, threshold=None, edgeitems=None,
modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal']
if floatmode not in modes + [None]:
raise ValueError("floatmode option must be one of " +
", ".join('"{}"'.format(m) for m in modes))
", ".join(f'"{m}"' for m in modes))

if sign not in [None, '-', '+', ' ']:
raise ValueError("sign option must be one of ' ', '+', or '-'")
Expand Down Expand Up @@ -926,7 +926,7 @@ def _none_or_positive_arg(x, name):
if x is None:
return -1
if x < 0:
raise ValueError("{} must be >= 0".format(name))
raise ValueError(f"{name} must be >= 0")
return x

class FloatingFormat:
Expand Down Expand Up @@ -1323,7 +1323,7 @@ def __init__(self, data):
if len(non_nat) < data.size:
# data contains a NaT
max_str_len = max(max_str_len, 5)
self._format = '%{}s'.format(max_str_len)
self._format = f'%{max_str_len}s'
self._nat = "'NaT'".rjust(max_str_len)

def _format_non_nat(self, x):
Expand Down Expand Up @@ -1432,9 +1432,10 @@ def __call__(self, x):
for field, format_function in zip(x, self.format_functions)
]
if len(str_fields) == 1:
return "({},)".format(str_fields[0])
return f"({str_fields[0]},)"
else:
return "({})".format(", ".join(str_fields))
all_str_fields = ', '.join(str_fields)
return f"({all_str_fields})"


def _void_scalar_to_string(x, is_repr=True):
Expand Down Expand Up @@ -1567,7 +1568,7 @@ def _array_repr_implementation(
if skipdtype:
return arr_str

dtype_str = "dtype={})".format(dtype_short_repr(arr.dtype))
dtype_str = f"dtype={dtype_short_repr(arr.dtype)})"

# compute whether we should put dtype on a new line: Do so if adding the
# dtype would extend the last line past max_line_width.
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/code_generators/genapi.py
Expand Up @@ -495,7 +495,7 @@ def check_api_dict(d):
doubled[index] = [name]
fmt = "Same index has been used twice in api definition: {}"
val = ''.join(
'\n\tindex {} -> {}'.format(index, names)
f'\n\tindex {index} -> {names}'
for index, names in doubled.items() if len(names) != 1
)
raise ValueError(fmt.format(val))
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/code_generators/generate_umath.py
Expand Up @@ -1478,7 +1478,7 @@ def make_ufuncs(funcdict):
if uf.signature is None:
sig = "NULL"
else:
sig = '"{}"'.format(uf.signature)
sig = f'"{uf.signature}"'
fmt = textwrap.dedent("""\
identity = {identity_expr};
if ({has_identity} && identity == NULL) {{
Expand Down
6 changes: 3 additions & 3 deletions numpy/_core/code_generators/ufunc_docstrings.py
Expand Up @@ -50,11 +50,11 @@ def add_newdoc(place, name, doc):
)
if name[0] != '_' and name not in skip:
if '\nx :' in doc:
assert '$OUT_SCALAR_1' in doc, "in {}".format(name)
assert '$OUT_SCALAR_1' in doc, f"in {name}"
elif '\nx2 :' in doc or '\nx1, x2 :' in doc:
assert '$OUT_SCALAR_2' in doc, "in {}".format(name)
assert '$OUT_SCALAR_2' in doc, f"in {name}"
else:
assert False, "Could not detect number of inputs in {}".format(name)
assert False, "Could not detect number of inputs in {name}"

for k, v in subst.items():
doc = doc.replace('$' + k, v)
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/fromnumeric.py
Expand Up @@ -539,7 +539,7 @@ def put(a, ind, v, mode='raise'):
put = a.put
except AttributeError as e:
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(a).__name__)) from e
f"not {type(a).__name__}") from e
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: i'm pretty sure this is how e.g. black would align it

Suggested change
f"not {type(a).__name__}") from e
f"not {type(a).__name__}") from e


return put(ind, v, mode=mode)

Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/numeric.py
Expand Up @@ -1424,7 +1424,7 @@ def normalize_axis_tuple(axis, ndim, argname=None, allow_duplicate=False):
axis = tuple([normalize_axis_index(ax, ndim, argname) for ax in axis])
if not allow_duplicate and len(set(axis)) != len(axis):
if argname:
raise ValueError('repeated axis in `{}` argument'.format(argname))
raise ValueError(f'repeated axis in `{argname}` argument')
else:
raise ValueError('repeated axis')
return axis
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/records.py
Expand Up @@ -126,7 +126,7 @@ def _parseFormats(self, formats, aligned=False):
if isinstance(formats, list):
dtype = sb.dtype(
[
('f{}'.format(i), format_)
(f'f{i}', format_)
for i, format_ in enumerate(formats)
],
aligned,
Expand Down