Skip to content

Commit 4784a52

Browse files
Change occurrences of format() to f-strings (#439)
* Change occurrences of format() to f-strings * Change occurrence of % to f-string * Update docs/release.rst * Apply and enforce ruff/pyupgrade rules (UP) UP006 Use `tuple` instead of `Tuple` for type annotation UP035 `typing.Dict` is deprecated, use `dict` instead UP035 `typing.Tuple` is deprecated, use `tuple` instead UP035 `typing.Type` is deprecated, use `type` instead
1 parent 729f84c commit 4784a52

18 files changed

+40
-65
lines changed

docs/release.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ Fix
2121

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

2527
* Remove pin on Sphinx
2628
By :user:`Elliott Sales de Andrade <QuLogic>`, :issue:`552`.

numcodecs/abc.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,9 @@ def __repr__(self):
118118
# by default, assume all non-private members are configuration
119119
# parameters and valid keyword arguments to constructor function
120120

121-
r = '%s(' % type(self).__name__
121+
r = f'{type(self).__name__}('
122122
params = [
123-
'{}={!r}'.format(k, getattr(self, k))
124-
for k in sorted(self.__dict__)
125-
if not k.startswith('_')
123+
f'{k}={getattr(self, k)!r}' for k in sorted(self.__dict__) if not k.startswith('_')
126124
]
127125
r += ', '.join(params) + ')'
128126
return r

numcodecs/astype.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,4 @@ def get_config(self):
7373
}
7474

7575
def __repr__(self):
76-
return '{}(encode_dtype={!r}, decode_dtype={!r})'.format(
77-
type(self).__name__, self.encode_dtype.str, self.decode_dtype.str
78-
)
76+
return f'{type(self).__name__}(encode_dtype={self.encode_dtype.str!r}, decode_dtype={self.decode_dtype.str!r})'

numcodecs/categorize.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,4 @@ def __repr__(self):
9999
labels = repr(self.labels[:3])
100100
if len(self.labels) > 3:
101101
labels = labels[:-1] + ', ...]'
102-
r = '%s(dtype=%r, astype=%r, labels=%s)' % (
103-
type(self).__name__,
104-
self.dtype.str,
105-
self.astype.str,
106-
labels,
107-
)
108-
return r
102+
return f'{type(self).__name__}(dtype={self.dtype.str!r}, astype={self.astype.str!r}, labels={labels})'

numcodecs/compat.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N
115115
raise ValueError("an array with contiguous memory is required")
116116

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

121121
return arr

numcodecs/delta.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,8 @@ def get_config(self):
9191
return dict(id=self.codec_id, dtype=self.dtype.str, astype=self.astype.str)
9292

9393
def __repr__(self):
94-
r = '{}(dtype={!r}'.format(type(self).__name__, self.dtype.str)
94+
r = f'{type(self).__name__}(dtype={self.dtype.str!r}'
9595
if self.astype != self.dtype:
96-
r += ', astype=%r' % self.astype.str
96+
r += f', astype={self.astype.str!r}'
9797
r += ')'
9898
return r

numcodecs/fixedscaleoffset.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,8 @@ def get_config(self):
126126
)
127127

128128
def __repr__(self):
129-
r = '%s(scale=%s, offset=%s, dtype=%r' % (
130-
type(self).__name__,
131-
self.scale,
132-
self.offset,
133-
self.dtype.str,
134-
)
129+
r = f'{type(self).__name__}(scale={self.scale}, offset={self.offset}, dtype={self.dtype.str!r}'
135130
if self.astype != self.dtype:
136-
r += ', astype=%r' % self.astype.str
131+
r += f', astype={self.astype.str!r}'
137132
r += ')'
138133
return r

numcodecs/json.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,13 @@ def get_config(self):
9797
return config
9898

9999
def __repr__(self):
100-
params = ['encoding=%r' % self._text_encoding]
100+
params = [f'encoding={self._text_encoding!r}']
101101
for k, v in sorted(self._encoder_config.items()):
102-
params.append('{}={!r}'.format(k, v))
102+
params.append(f'{k}={v!r}')
103103
for k, v in sorted(self._decoder_config.items()):
104-
params.append('{}={!r}'.format(k, v))
104+
params.append(f'{k}={v!r}')
105105
classname = type(self).__name__
106-
r = '{}({})'.format(classname, ', '.join(params))
107-
r = textwrap.fill(r, width=80, break_long_words=False, subsequent_indent=' ')
108-
return r
106+
params = ', '.join(params)
107+
return textwrap.fill(
108+
f'{classname}({params})', width=80, break_long_words=False, subsequent_indent=' '
109+
)

numcodecs/lzma.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,11 +66,4 @@ def decode(self, buf, out=None):
6666
return ndarray_copy(dec, out)
6767

6868
def __repr__(self):
69-
r = '%s(format=%r, check=%r, preset=%r, filters=%r)' % (
70-
type(self).__name__,
71-
self.format,
72-
self.check,
73-
self.preset,
74-
self.filters,
75-
)
76-
return r
69+
return f'{type(self).__name__}(format={self.format!r}, check={self.check!r}, preset={self.preset!r}, filters={self.filters!r})'

numcodecs/msgpacks.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,4 @@ def get_config(self):
8484
)
8585

8686
def __repr__(self):
87-
return 'MsgPack(raw={!r}, use_bin_type={!r}, use_single_float={!r})'.format(
88-
self.raw, self.use_bin_type, self.use_single_float
89-
)
87+
return f'MsgPack(raw={self.raw!r}, use_bin_type={self.use_bin_type!r}, use_single_float={self.use_single_float!r})'

numcodecs/ndarray_like.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, Dict, Optional, Protocol, Tuple, Type, runtime_checkable
1+
from typing import Any, Optional, Protocol, runtime_checkable
22

33

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

14-
_instancecheck_cache: Dict[Tuple[Type, Type], bool] = {}
14+
_instancecheck_cache: dict[tuple[type, type], bool] = {}
1515

1616
def __instancecheck__(self, instance):
1717
key = (self, instance.__class__)
@@ -39,8 +39,8 @@ class FlagsObj(Protocol, metaclass=_CachedProtocolMeta):
3939
@runtime_checkable
4040
class NDArrayLike(Protocol, metaclass=_CachedProtocolMeta):
4141
dtype: DType
42-
shape: Tuple[int, ...]
43-
strides: Tuple[int, ...]
42+
shape: tuple[int, ...]
43+
strides: tuple[int, ...]
4444
ndim: int
4545
size: int
4646
itemsize: int

numcodecs/pickles.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,4 @@ def get_config(self):
5252
return dict(id=self.codec_id, protocol=self.protocol)
5353

5454
def __repr__(self):
55-
return 'Pickle(protocol=%s)' % self.protocol
55+
return f'Pickle(protocol={self.protocol})'

numcodecs/quantize.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,8 @@ def get_config(self):
9595
)
9696

9797
def __repr__(self):
98-
r = '%s(digits=%s, dtype=%r' % (
99-
type(self).__name__,
100-
self.digits,
101-
self.dtype.str,
102-
)
98+
r = f'{type(self).__name__}(digits={self.digits}, dtype={self.dtype.str!r}'
10399
if self.astype != self.dtype:
104-
r += ', astype=%r' % self.astype.str
100+
r += f', astype={self.astype.str!r}'
105101
r += ')'
106102
return r

numcodecs/registry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def get_codec(config):
4949
register_codec(cls, codec_id=codec_id)
5050
if cls:
5151
return cls.from_config(config)
52-
raise ValueError('codec not available: %r' % codec_id)
52+
raise ValueError(f'codec not available: {codec_id!r}')
5353

5454

5555
def register_codec(cls, codec_id=None):

numcodecs/shuffle.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,5 +57,4 @@ def decode(self, buf, out=None):
5757
return out
5858

5959
def __repr__(self):
60-
r = '%s(elementsize=%s)' % (type(self).__name__, self.elementsize)
61-
return r
60+
return f'{type(self).__name__}(elementsize={self.elementsize})'

numcodecs/tests/common.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def check_backwards_compatibility(codec_id, arrays, codecs, precision=None, pref
258258

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

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

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

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

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

298298
# one time encode and save array
299299
if not os.path.exists(enc_fn): # pragma: no cover

numcodecs/zfpy.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,8 @@ def decode(self, buf, out=None):
102102
return dec
103103

104104
def __repr__(self):
105-
r = "%s(mode=%r, tolerance=%s, rate=%s, precision=%s)" % (
106-
type(self).__name__,
107-
self.mode,
108-
self.tolerance,
109-
self.rate,
110-
self.precision,
105+
return (
106+
f"{type(self).__name__}(mode={self.mode!r}, "
107+
f"tolerance={self.tolerance}, rate={self.rate}, "
108+
f"precision={self.precision})"
111109
)
112-
return r

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,5 +131,9 @@ environment = { DISABLE_NUMCODECS_AVX2=1, DISABLE_NUMCODECS_SSE2=1 }
131131
[tool.ruff]
132132
line-length = 100
133133

134+
[tool.ruff.lint]
135+
extend-select = [ "UP" ]
136+
ignore = ["UP007"]
137+
134138
[tool.ruff.format]
135139
quote-style = "preserve"

0 commit comments

Comments
 (0)