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 6 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
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
2 changes: 1 addition & 1 deletion numpy/__init__.py
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
8 changes: 4 additions & 4 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 @@ -367,7 +367,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__}")
8 changes: 4 additions & 4 deletions numpy/_core/_internal.py
Expand Up @@ -881,9 +881,9 @@ def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):

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 @@ -907,7 +907,7 @@ def _ufunc_doc_signature_formatter(ufunc):
else:
out_args = '[, {positional}], / [, out={default}]'.format(
positional=', '.join(
'out{}'.format(i+1) for i in range(ufunc.nout)),
f'out{i+1}' for i in range(ufunc.nout)),
default=repr((None,)*ufunc.nout)
)

Expand Down
12 changes: 6 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,9 @@ 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]},)".format(str_fields[0])
HenryAsa marked this conversation as resolved.
Show resolved Hide resolved
else:
return "({})".format(", ".join(str_fields))
return f"({', '.join(str_fields)})"


def _void_scalar_to_string(x, is_repr=True):
Expand Down Expand Up @@ -1567,7 +1567,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/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
17 changes: 6 additions & 11 deletions numpy/_core/shape_base.py
Expand Up @@ -469,7 +469,7 @@ def _block_format_index(index):
"""
Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``.
"""
idx_str = ''.join('[{}]'.format(i) for i in index if i is not None)
idx_str = ''.join(f'[{i}]' for i in index if i is not None)
return 'arrays' + idx_str


Expand Down Expand Up @@ -529,11 +529,8 @@ def _block_check_depths_match(arrays, parent_index=[]):
if len(index) != len(first_index):
raise ValueError(
"List depths are mismatched. First element was at depth "
"{}, but there is an element at depth {} ({})".format(
len(first_index),
len(index),
_block_format_index(index)
)
f"{len(first_index)}, but there is an element at depth "
f"{len(index)} ({_block_format_index(index)})"
)
# propagate our flag that indicates an empty list at the bottom
if index[-1] is None:
Expand Down Expand Up @@ -605,9 +602,9 @@ def _concatenate_shapes(shapes, axis):
if any(shape[:axis] != first_shape_pre or
shape[axis+1:] != first_shape_post for shape in shapes):
raise ValueError(
'Mismatched array shapes in block along axis {}.'.format(axis))
f'Mismatched array shapes in block along axis {axis}.')

shape = (first_shape_pre + (sum(shape_at_axis),) + first_shape[axis+1:])
shape = first_shape_pre + (sum(shape_at_axis),) + first_shape[axis+1:]
HenryAsa marked this conversation as resolved.
Show resolved Hide resolved

offsets_at_axis = _accumulate(shape_at_axis)
slice_prefixes = [(slice(start, end),)
Expand Down Expand Up @@ -885,9 +882,7 @@ def _block_setup(arrays):
list_ndim = len(bottom_index)
if bottom_index and bottom_index[-1] is None:
raise ValueError(
'List at {} cannot be empty'.format(
_block_format_index(bottom_index)
)
f'List at {_block_format_index(bottom_index)} cannot be empty'
)
result_ndim = max(arr_ndim, list_ndim)
return arrays, list_ndim, result_ndim, final_size
Expand Down
8 changes: 4 additions & 4 deletions numpy/_core/tests/test_arrayprint.py
Expand Up @@ -799,7 +799,7 @@ def test_floatmode(self):
c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16')

# also make sure 1e23 is right (is between two fp numbers)
w = np.array(['1e{}'.format(i) for i in range(25)], dtype=np.float64)
w = np.array([f'1e{i}' for i in range(25)], dtype=np.float64)
# note: we construct w from the strings `1eXX` instead of doing
# `10.**arange(24)` because it turns out the two are not equivalent in
# python. On some architectures `1e23 != 10.**23`.
Expand Down Expand Up @@ -911,10 +911,10 @@ def test_dtype_linewidth_wrapping(self):

styp = '<U4'
assert_equal(repr(np.ones(3, dtype=styp)),
"array(['1', '1', '1'], dtype='{}')".format(styp))
assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent("""\
f"array(['1', '1', '1'], dtype='{styp}')")
assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent(f"""\
array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
dtype='{}')""".format(styp)))
dtype='{styp}')"""))

@pytest.mark.parametrize(
['native'],
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_deprecations.py
Expand Up @@ -258,7 +258,7 @@ def test_deprecate_unparsable_data_file(self, invalid_str):
@pytest.mark.parametrize("invalid_str", [",invalid_data", "invalid_sep"])
def test_deprecate_unparsable_string(self, invalid_str):
x = np.array([1.51, 2, 3.51, 4], dtype=float)
x_str = "1.51,2,3.51,4{}".format(invalid_str)
x_str = f"1.51,2,3.51,4{invalid_str}"

self.assert_deprecated(lambda: np.fromstring(x_str, sep=","))
self.assert_deprecated(lambda: np.fromstring(x_str, sep=",", count=5))
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_multiarray.py
Expand Up @@ -9263,7 +9263,7 @@ def test_0d(self):

def test_1d_no_format(self):
a = np.array([np.pi])
assert_equal('{}'.format(a), str(a))
assert_equal(f'{a}', str(a))

def test_1d_format(self):
# until gh-5543, ensure that the behaviour matches what it used to be
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_scalar_methods.py
Expand Up @@ -105,7 +105,7 @@ def test_roundtrip(self, ftype, frac_vals, exp_vals):
# the values may not fit in any float type
pytest.skip("longdouble too small on this platform")

assert_equal(nf / df, f, "{}/{}".format(n, d))
assert_equal(nf / df, f, f"{n}/{d}")


class TestIsInteger:
Expand Down
2 changes: 1 addition & 1 deletion numpy/_core/tests/test_scalarprint.py
Expand Up @@ -25,7 +25,7 @@ def test_str(self):

for wants, val in zip(wanted, svals):
for want, styp in zip(wants, styps):
msg = 'for str({}({}))'.format(np.dtype(styp).name, repr(val))
msg = f'for str({np.dtype(styp).name}({repr(val)}))'
assert_equal(str(styp(val)), want, err_msg=msg)

def test_scalar_cutoffs(self):
Expand Down
4 changes: 2 additions & 2 deletions numpy/_core/tests/test_umath.py
Expand Up @@ -3069,8 +3069,8 @@ def do_test(f_call, f_expected):
# assert_equal produces truly useless error messages
raise AssertionError("\n".join([
"Bad arguments passed in ufunc call",
" expected: {}".format(expected),
" __array_wrap__ got: {}".format(w)
f" expected: {expected}"
f" __array_wrap__ got: {w}"
]))

# method not on the out argument
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/fcompiler/intel.py
Expand Up @@ -60,7 +60,7 @@ def get_flags_opt(self): # Scipy test failures with -O2
v = self.get_version()
mpopt = 'openmp' if v and v < '15' else 'qopenmp'
return ['-fp-model', 'strict', '-O1',
'-assume', 'minus0', '-{}'.format(mpopt)]
'-assume', 'minus0', f'-{mpopt}']

def get_flags_arch(self):
return []
Expand Down
14 changes: 8 additions & 6 deletions numpy/distutils/system_info.py
Expand Up @@ -229,7 +229,7 @@ def _c_string_literal(s):
s = s.replace('\\', r'\\')
s = s.replace('"', r'\"')
s = s.replace('\n', r'\n')
return '"{}"'.format(s)
return f'"{s}"'


def libpaths(paths, bits):
Expand Down Expand Up @@ -819,7 +819,7 @@ def get_option_single(self, *options):
if AliasedOptionError.__doc__ is None:
raise AliasedOptionError()
raise AliasedOptionError(AliasedOptionError.__doc__.format(
section=self.section, options='[{}]'.format(', '.join(options))))
section=self.section, options=f'[{", ".join(options)}]'))


def has_info(self):
Expand Down Expand Up @@ -1971,14 +1971,14 @@ def _calc_info_from_envvar(self):
return True

def _calc_info(self, name):
return getattr(self, '_calc_info_{}'.format(name))()
return getattr(self, f'_calc_info_{name}')()

def calc_info(self):
lapack_order, unknown_order = _parse_env_order(self.lapack_order, self.order_env_var_name)
if len(unknown_order) > 0:
raise ValueError("lapack_opt_info user defined "
"LAPACK order has unacceptable "
"values: {}".format(unknown_order))
f"values: {unknown_order}")

if 'NPY_LAPACK_LIBS' in os.environ:
# Bypass autodetection, set language to F77 and use env var linker
Expand Down Expand Up @@ -2142,12 +2142,14 @@ def _calc_info_from_envvar(self):
return True

def _calc_info(self, name):
return getattr(self, '_calc_info_{}'.format(name))()
return getattr(self, f'_calc_info_{name}')()

def calc_info(self):
blas_order, unknown_order = _parse_env_order(self.blas_order, self.order_env_var_name)
if len(unknown_order) > 0:
raise ValueError("blas_opt_info user defined BLAS order has unacceptable values: {}".format(unknown_order))
raise ValueError(
f"blas_opt_info user defined BLAS order "
HenryAsa marked this conversation as resolved.
Show resolved Hide resolved
f"has unacceptable values: {unknown_order}")

if 'NPY_BLAS_LIBS' in os.environ:
# Bypass autodetection, set language to F77 and use env var linker
Expand Down
4 changes: 2 additions & 2 deletions numpy/distutils/tests/test_fcompiler.py
Expand Up @@ -18,7 +18,7 @@ def test_fcompiler_flags(monkeypatch):
flag_vars = fc.flag_vars.clone(lambda *args, **kwargs: None)

for opt, envvar in customizable_flags:
new_flag = '-dummy-{}-flag'.format(opt)
new_flag = f'-dummy-{opt}-flag'
prev_flags = getattr(flag_vars, opt)

monkeypatch.setenv(envvar, new_flag)
Expand All @@ -30,7 +30,7 @@ def test_fcompiler_flags(monkeypatch):
monkeypatch.setenv('NPY_DISTUTILS_APPEND_FLAGS', '1')

for opt, envvar in customizable_flags:
new_flag = '-dummy-{}-flag'.format(opt)
new_flag = f'-dummy-{opt}-flag'
prev_flags = getattr(flag_vars, opt)
monkeypatch.setenv(envvar, new_flag)
new_flags = getattr(flag_vars, opt)
Expand Down
4 changes: 2 additions & 2 deletions numpy/f2py/_src_pyf.py
Expand Up @@ -165,8 +165,8 @@ def listrepl(mobj):
elif num == numsubs:
rules[r] = rule
else:
print("Mismatch in number of replacements (base <{}={}>) "
"for <{}={}>. Ignoring.".format(base_rule, ','.join(rules[base_rule]), r, thelist))
print(f"Mismatch in number of replacements (base <{base_rule}={','.join(rules[base_rule])}>) "
f"for <{r}={thelist}>. Ignoring.")
if not rules:
return substr

Expand Down