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

Change occurrences of format() to f-strings #439

Merged
merged 4 commits into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ Fix

Maintenance
~~~~~~~~~~~
* Change format() and old string formatting to f-strings.
By :user:`Dimitri Papadopoulos Orfanos <DimitriPapadopoulos>`, :issue:`439`.

* Remove pin on Sphinx
By :user:`Elliott Sales de Andrade <QuLogic>`, :issue:`552`.
Expand Down
6 changes: 2 additions & 4 deletions numcodecs/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,9 @@ def __repr__(self):
# by default, assume all non-private members are configuration
# parameters and valid keyword arguments to constructor function

r = '%s(' % type(self).__name__
r = f'{type(self).__name__}('
params = [
'{}={!r}'.format(k, getattr(self, k))
for k in sorted(self.__dict__)
if not k.startswith('_')
f'{k}={getattr(self, k)!r}' for k in sorted(self.__dict__) if not k.startswith('_')
]
r += ', '.join(params) + ')'
return r
4 changes: 1 addition & 3 deletions numcodecs/astype.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,4 @@ def get_config(self):
}

def __repr__(self):
return '{}(encode_dtype={!r}, decode_dtype={!r})'.format(
type(self).__name__, self.encode_dtype.str, self.decode_dtype.str
)
return f'{type(self).__name__}(encode_dtype={self.encode_dtype.str!r}, decode_dtype={self.decode_dtype.str!r})'
8 changes: 1 addition & 7 deletions numcodecs/categorize.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,4 @@ def __repr__(self):
labels = repr(self.labels[:3])
if len(self.labels) > 3:
labels = labels[:-1] + ', ...]'
r = '%s(dtype=%r, astype=%r, labels=%s)' % (
type(self).__name__,
self.dtype.str,
self.astype.str,
labels,
)
return r
return f'{type(self).__name__}(dtype={self.dtype.str!r}, astype={self.astype.str!r}, labels={labels})'
2 changes: 1 addition & 1 deletion numcodecs/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N
raise ValueError("an array with contiguous memory is required")

if max_buffer_size is not None and arr.nbytes > max_buffer_size:
msg = "Codec does not support buffers of > {} bytes".format(max_buffer_size)
msg = f"Codec does not support buffers of > {max_buffer_size} bytes"
raise ValueError(msg)

return arr
Expand Down
4 changes: 2 additions & 2 deletions numcodecs/delta.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ def get_config(self):
return dict(id=self.codec_id, dtype=self.dtype.str, astype=self.astype.str)

def __repr__(self):
r = '{}(dtype={!r}'.format(type(self).__name__, self.dtype.str)
r = f'{type(self).__name__}(dtype={self.dtype.str!r}'
if self.astype != self.dtype:
r += ', astype=%r' % self.astype.str
r += f', astype={self.astype.str!r}'
r += ')'
return r
9 changes: 2 additions & 7 deletions numcodecs/fixedscaleoffset.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,8 @@ def get_config(self):
)

def __repr__(self):
r = '%s(scale=%s, offset=%s, dtype=%r' % (
type(self).__name__,
self.scale,
self.offset,
self.dtype.str,
)
r = f'{type(self).__name__}(scale={self.scale}, offset={self.offset}, dtype={self.dtype.str!r}'
if self.astype != self.dtype:
r += ', astype=%r' % self.astype.str
r += f', astype={self.astype.str!r}'
r += ')'
return r
13 changes: 7 additions & 6 deletions numcodecs/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,13 @@ def get_config(self):
return config

def __repr__(self):
params = ['encoding=%r' % self._text_encoding]
params = [f'encoding={self._text_encoding!r}']
for k, v in sorted(self._encoder_config.items()):
params.append('{}={!r}'.format(k, v))
params.append(f'{k}={v!r}')
for k, v in sorted(self._decoder_config.items()):
params.append('{}={!r}'.format(k, v))
params.append(f'{k}={v!r}')
classname = type(self).__name__
r = '{}({})'.format(classname, ', '.join(params))
r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ')
return r
params = ', '.join(params)
return textwrap.fill(
f'{classname}({params})', width=80, break_long_words=False, subsequent_indent=' '
)
9 changes: 1 addition & 8 deletions numcodecs/lzma.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,4 @@ def decode(self, buf, out=None):
return ndarray_copy(dec, out)

def __repr__(self):
r = '%s(format=%r, check=%r, preset=%r, filters=%r)' % (
type(self).__name__,
self.format,
self.check,
self.preset,
self.filters,
)
return r
return f'{type(self).__name__}(format={self.format!r}, check={self.check!r}, preset={self.preset!r}, filters={self.filters!r})'
4 changes: 1 addition & 3 deletions numcodecs/msgpacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,4 @@ def get_config(self):
)

def __repr__(self):
return 'MsgPack(raw={!r}, use_bin_type={!r}, use_single_float={!r})'.format(
self.raw, self.use_bin_type, self.use_single_float
)
return f'MsgPack(raw={self.raw!r}, use_bin_type={self.use_bin_type!r}, use_single_float={self.use_single_float!r})'
8 changes: 4 additions & 4 deletions numcodecs/ndarray_like.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict, Optional, Protocol, Tuple, Type, runtime_checkable
from typing import Any, Optional, Protocol, runtime_checkable


class _CachedProtocolMeta(Protocol.__class__):
Expand All @@ -11,7 +11,7 @@ class _CachedProtocolMeta(Protocol.__class__):
isinstance checks using the object's class as the cache key.
"""

_instancecheck_cache: Dict[Tuple[Type, Type], bool] = {}
_instancecheck_cache: dict[tuple[type, type], bool] = {}

def __instancecheck__(self, instance):
key = (self, instance.__class__)
Expand Down Expand Up @@ -39,8 +39,8 @@ class FlagsObj(Protocol, metaclass=_CachedProtocolMeta):
@runtime_checkable
class NDArrayLike(Protocol, metaclass=_CachedProtocolMeta):
dtype: DType
shape: Tuple[int, ...]
strides: Tuple[int, ...]
shape: tuple[int, ...]
strides: tuple[int, ...]
ndim: int
size: int
itemsize: int
Expand Down
2 changes: 1 addition & 1 deletion numcodecs/pickles.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,4 @@ def get_config(self):
return dict(id=self.codec_id, protocol=self.protocol)

def __repr__(self):
return 'Pickle(protocol=%s)' % self.protocol
return f'Pickle(protocol={self.protocol})'
8 changes: 2 additions & 6 deletions numcodecs/quantize.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,8 @@ def get_config(self):
)

def __repr__(self):
r = '%s(digits=%s, dtype=%r' % (
type(self).__name__,
self.digits,
self.dtype.str,
)
r = f'{type(self).__name__}(digits={self.digits}, dtype={self.dtype.str!r}'
if self.astype != self.dtype:
r += ', astype=%r' % self.astype.str
r += f', astype={self.astype.str!r}'
r += ')'
return r
2 changes: 1 addition & 1 deletion numcodecs/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def get_codec(config):
register_codec(cls, codec_id=codec_id)
if cls:
return cls.from_config(config)
raise ValueError('codec not available: %r' % codec_id)
raise ValueError(f'codec not available: {codec_id!r}')


def register_codec(cls, codec_id=None):
Expand Down
3 changes: 1 addition & 2 deletions numcodecs/shuffle.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,4 @@ def decode(self, buf, out=None):
return out

def __repr__(self):
r = '%s(elementsize=%s)' % (type(self).__name__, self.elementsize)
return r
return f'{type(self).__name__}(elementsize={self.elementsize})'
6 changes: 3 additions & 3 deletions numcodecs/tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, pref

# save fixture data
for i, arr in enumerate(arrays):
arr_fn = os.path.join(fixture_dir, 'array.{:02d}.npy'.format(i))
arr_fn = os.path.join(fixture_dir, f'array.{i:02d}.npy')
if not os.path.exists(arr_fn): # pragma: no cover
np.save(arr_fn, arr)

Expand All @@ -278,7 +278,7 @@ def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, pref
pytest.skip("codec has been removed")

# setup a directory to hold encoded data
codec_dir = os.path.join(fixture_dir, 'codec.{:02d}'.format(j))
codec_dir = os.path.join(fixture_dir, f'codec.{j:02d}')
if not os.path.exists(codec_dir): # pragma: no cover
os.makedirs(codec_dir)

Expand All @@ -293,7 +293,7 @@ def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, pref
config = _json.load(cf)
assert codec == get_codec(config)

enc_fn = os.path.join(codec_dir, 'encoded.{:02d}.dat'.format(i))
enc_fn = os.path.join(codec_dir, f'encoded.{i:02d}.dat')

# one time encode and save array
if not os.path.exists(enc_fn): # pragma: no cover
Expand Down
11 changes: 4 additions & 7 deletions numcodecs/zfpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,8 @@ def decode(self, buf, out=None):
return dec

def __repr__(self):
r = "%s(mode=%r, tolerance=%s, rate=%s, precision=%s)" % (
type(self).__name__,
self.mode,
self.tolerance,
self.rate,
self.precision,
return (
f"{type(self).__name__}(mode={self.mode!r}, "
f"tolerance={self.tolerance}, rate={self.rate}, "
f"precision={self.precision})"
)
return r
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,9 @@ environment = { DISABLE_NUMCODECS_AVX2=1, DISABLE_NUMCODECS_SSE2=1 }
[tool.ruff]
line-length = 100

[tool.ruff.lint]
extend-select = [ "UP" ]
ignore = ["UP007"]

[tool.ruff.format]
quote-style = "preserve"