Skip to content

Commit 3bb2aeb

Browse files
Change occurrences of % and format() to f-strings
1 parent e771c51 commit 3bb2aeb

18 files changed

+177
-238
lines changed

docs/release.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ Docs
3030
Maintenance
3131
~~~~~~~~~~~
3232

33+
* Change occurrences of % and format() to f-strings.
34+
By :user:`Dimitri Papadopoulos Orfanos <DimitriPapadopoulos>` :issue:`1423`.
35+
3336
* Change occurrence of ``io.open()`` into ``open()``.
3437
By :user:`Dimitri Papadopoulos Orfanos <DimitriPapadopoulos>` :issue:`1421`.
3538

@@ -42,8 +45,6 @@ Maintenance
4245
* Allow ``black`` code formatter to be run with any Python version.
4346
By :user:`David Stansby <dstansby>` :issue:`1549`.
4447

45-
46-
4748
.. _release_2.16.1:
4849

4950
2.16.1

zarr/_storage/absstore.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,10 @@ def __init__(
8484

8585
blob_service_kwargs = blob_service_kwargs or {}
8686
client = ContainerClient(
87-
"https://{}.blob.core.windows.net/".format(account_name),
87+
f"https://{account_name}.blob.core.windows.net/",
8888
container,
8989
credential=account_key,
90-
**blob_service_kwargs
90+
**blob_service_kwargs,
9191
)
9292

9393
self.client = client
@@ -141,7 +141,7 @@ def __getitem__(self, key):
141141
try:
142142
return self.client.download_blob(blob_name).readall()
143143
except ResourceNotFoundError:
144-
raise KeyError("Blob %s not found" % blob_name)
144+
raise KeyError(f"Blob {blob_name} not found")
145145

146146
def __setitem__(self, key, value):
147147
value = ensure_bytes(value)
@@ -154,7 +154,7 @@ def __delitem__(self, key):
154154
try:
155155
self.client.delete_blob(self._append_path_to_prefix(key))
156156
except ResourceNotFoundError:
157-
raise KeyError("Blob %s not found" % key)
157+
raise KeyError(f"Blob {key} not found")
158158

159159
def __eq__(self, other):
160160
return (

zarr/_storage/store.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ def _validate_key(self, key: str):
227227
# TODO: Possibly allow key == ".zmetadata" too if we write a
228228
# consolidated metadata spec corresponding to this?
229229
):
230-
raise ValueError("keys starts with unexpected value: `{}`".format(key))
230+
raise ValueError(f"key starts with unexpected value: `{key}`")
231231

232232
if key.endswith("/"):
233233
raise ValueError("keys may not end in /")

zarr/_storage/v3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,7 +570,7 @@ def __init__(self, store: StoreLike, metadata_key=meta_root + "consolidated/.zme
570570
consolidated_format = meta.get("zarr_consolidated_format", None)
571571
if consolidated_format != 1:
572572
raise MetadataError(
573-
"unsupported zarr consolidated metadata format: %s" % consolidated_format
573+
f"unsupported zarr consolidated metadata format: {consolidated_format}"
574574
)
575575

576576
# decode metadata

zarr/convenience.py

Lines changed: 23 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def save_group(store: StoreLike, *args, zarr_version=None, path=None, **kwargs):
258258
try:
259259
grp = _create_group(_store, path=path, overwrite=True, zarr_version=zarr_version)
260260
for i, arr in enumerate(args):
261-
k = "arr_{}".format(i)
261+
k = f"arr_{i}"
262262
grp.create_dataset(k, data=arr, overwrite=True, zarr_version=zarr_version)
263263
for k, arr in kwargs.items():
264264
grp.create_dataset(k, data=arr, overwrite=True, zarr_version=zarr_version)
@@ -498,7 +498,7 @@ def __init__(self, log):
498498
self.log_file = log
499499
else:
500500
raise TypeError(
501-
"log must be a callable function, file path or " "file-like object, found %r" % log
501+
f"log must be a callable function, file path or file-like object, found {log!r}"
502502
)
503503

504504
def __enter__(self):
@@ -525,9 +525,9 @@ def _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied):
525525
message = "dry run: "
526526
else:
527527
message = "all done: "
528-
message += "{:,} copied, {:,} skipped".format(n_copied, n_skipped)
528+
message += f"{n_copied:,} copied, {n_skipped:,} skipped"
529529
if not dry_run:
530-
message += ", {:,} bytes copied".format(n_bytes_copied)
530+
message += f", {n_bytes_copied:,} bytes copied"
531531
log(message)
532532

533533

@@ -656,9 +656,7 @@ def copy_store(
656656
# check if_exists parameter
657657
valid_if_exists = ["raise", "replace", "skip"]
658658
if if_exists not in valid_if_exists:
659-
raise ValueError(
660-
"if_exists must be one of {!r}; found {!r}".format(valid_if_exists, if_exists)
661-
)
659+
raise ValueError(f"if_exists must be one of {valid_if_exists!r}; found {if_exists!r}")
662660

663661
# setup counting variables
664662
n_copied = n_skipped = n_bytes_copied = 0
@@ -721,20 +719,20 @@ def copy_store(
721719
if if_exists != "replace":
722720
if dest_key in dest:
723721
if if_exists == "raise":
724-
raise CopyError("key {!r} exists in destination".format(dest_key))
722+
raise CopyError(f"key {dest_key!r} exists in destination")
725723
elif if_exists == "skip":
726724
do_copy = False
727725

728726
# take action
729727
if do_copy:
730-
log("copy {}".format(descr))
728+
log(f"copy {descr}")
731729
if not dry_run:
732730
data = source[source_key]
733731
n_bytes_copied += buffer_size(data)
734732
dest[dest_key] = data
735733
n_copied += 1
736734
else:
737-
log("skip {}".format(descr))
735+
log(f"skip {descr}")
738736
n_skipped += 1
739737

740738
# log a final message with a summary of what happened
@@ -745,7 +743,7 @@ def copy_store(
745743

746744
def _check_dest_is_group(dest):
747745
if not hasattr(dest, "create_dataset"):
748-
raise ValueError("dest must be a group, got {!r}".format(dest))
746+
raise ValueError(f"dest must be a group, got {dest!r}")
749747

750748

751749
def copy(
@@ -757,7 +755,7 @@ def copy(
757755
log=None,
758756
if_exists="raise",
759757
dry_run=False,
760-
**create_kws
758+
**create_kws,
761759
):
762760
"""Copy the `source` array or group into the `dest` group.
763761
@@ -890,7 +888,7 @@ def copy(
890888
without_attrs=without_attrs,
891889
if_exists=if_exists,
892890
dry_run=dry_run,
893-
**create_kws
891+
**create_kws,
894892
)
895893

896894
# log a final message with a summary of what happened
@@ -912,11 +910,9 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
912910
# check if_exists parameter
913911
valid_if_exists = ["raise", "replace", "skip", "skip_initialized"]
914912
if if_exists not in valid_if_exists:
915-
raise ValueError(
916-
"if_exists must be one of {!r}; found {!r}".format(valid_if_exists, if_exists)
917-
)
913+
raise ValueError(f"if_exists must be one of {valid_if_exists!r}; found {if_exists!r}")
918914
if dest_h5py and if_exists == "skip_initialized":
919-
raise ValueError("{!r} can only be used when copying to zarr".format(if_exists))
915+
raise ValueError(f"{if_exists!r} can only be used when copying to zarr")
920916

921917
# determine name to copy to
922918
if name is None:
@@ -936,9 +932,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
936932
exists = dest is not None and name in dest
937933
if exists:
938934
if if_exists == "raise":
939-
raise CopyError(
940-
"an object {!r} already exists in destination " "{!r}".format(name, dest.name)
941-
)
935+
raise CopyError(f"an object {name!r} already exists in destination {dest.name!r}")
942936
elif if_exists == "skip":
943937
do_copy = False
944938
elif if_exists == "skip_initialized":
@@ -950,7 +944,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
950944
if do_copy:
951945

952946
# log a message about what we're going to do
953-
log("copy {} {} {}".format(source.name, source.shape, source.dtype))
947+
log(f"copy {source.name} {source.shape} {source.dtype}")
954948

955949
if not dry_run:
956950

@@ -1019,7 +1013,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10191013
n_copied += 1
10201014

10211015
else:
1022-
log("skip {} {} {}".format(source.name, source.shape, source.dtype))
1016+
log(f"skip {source.name} {source.shape} {source.dtype}")
10231017
n_skipped += 1
10241018

10251019
elif root or not shallow:
@@ -1030,17 +1024,15 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10301024
exists_array = dest is not None and name in dest and hasattr(dest[name], "shape")
10311025
if exists_array:
10321026
if if_exists == "raise":
1033-
raise CopyError(
1034-
"an array {!r} already exists in destination " "{!r}".format(name, dest.name)
1035-
)
1027+
raise CopyError(f"an array {name!r} already exists in destination {dest.name!r}")
10361028
elif if_exists == "skip":
10371029
do_copy = False
10381030

10391031
# take action
10401032
if do_copy:
10411033

10421034
# log action
1043-
log("copy {}".format(source.name))
1035+
log(f"copy {source.name}")
10441036

10451037
if not dry_run:
10461038

@@ -1076,7 +1068,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10761068
without_attrs=without_attrs,
10771069
if_exists=if_exists,
10781070
dry_run=dry_run,
1079-
**create_kws
1071+
**create_kws,
10801072
)
10811073
n_copied += c
10821074
n_skipped += s
@@ -1085,7 +1077,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10851077
n_copied += 1
10861078

10871079
else:
1088-
log("skip {}".format(source.name))
1080+
log(f"skip {source.name}")
10891081
n_skipped += 1
10901082

10911083
return n_copied, n_skipped, n_bytes_copied
@@ -1099,7 +1091,7 @@ def copy_all(
10991091
log=None,
11001092
if_exists="raise",
11011093
dry_run=False,
1102-
**create_kws
1094+
**create_kws,
11031095
):
11041096
"""Copy all children of the `source` group into the `dest` group.
11051097
@@ -1201,7 +1193,7 @@ def copy_all(
12011193
without_attrs=without_attrs,
12021194
if_exists=if_exists,
12031195
dry_run=dry_run,
1204-
**create_kws
1196+
**create_kws,
12051197
)
12061198
n_copied += c
12071199
n_skipped += s
@@ -1336,7 +1328,7 @@ def open_consolidated(store: StoreLike, metadata_key=".zmetadata", mode="r+", **
13361328
store, storage_options=kwargs.get("storage_options"), mode=mode, zarr_version=zarr_version
13371329
)
13381330
if mode not in {"r", "r+"}:
1339-
raise ValueError("invalid mode, expected either 'r' or 'r+'; found {!r}".format(mode))
1331+
raise ValueError(f"invalid mode, expected either 'r' or 'r+'; found {mode!r}")
13401332

13411333
path = kwargs.pop("path", None)
13421334
if store._store_version == 2:

zarr/core.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2448,11 +2448,11 @@ def _encode_chunk(self, chunk):
24482448

24492449
def __repr__(self):
24502450
t = type(self)
2451-
r = "<{}.{}".format(t.__module__, t.__name__)
2451+
r = f"<{t.__module__}.{t.__name__}"
24522452
if self.name:
2453-
r += " %r" % self.name
2454-
r += " %s" % str(self.shape)
2455-
r += " %s" % self.dtype
2453+
r += f" {self.name!r}"
2454+
r += f" {str(self.shape)}"
2455+
r += f" {self.dtype}"
24562456
if self._read_only:
24572457
r += " read-only"
24582458
r += ">"
@@ -2488,11 +2488,11 @@ def info_items(self):
24882488

24892489
def _info_items_nosync(self):
24902490
def typestr(o):
2491-
return "{}.{}".format(type(o).__module__, type(o).__name__)
2491+
return f"{type(o).__module__}.{type(o).__name__}"
24922492

24932493
def bytestr(n):
24942494
if n > 2**10:
2495-
return "{} ({})".format(n, human_readable_size(n))
2495+
return f"{n} ({human_readable_size(n)})"
24962496
else:
24972497
return str(n)
24982498

@@ -2503,7 +2503,7 @@ def bytestr(n):
25032503
items += [("Name", self.name)]
25042504
items += [
25052505
("Type", typestr(self)),
2506-
("Data type", "%s" % self.dtype),
2506+
("Data type", str(self.dtype)),
25072507
("Shape", str(self.shape)),
25082508
("Chunk shape", str(self.chunks)),
25092509
("Order", self.order),
@@ -2513,7 +2513,7 @@ def bytestr(n):
25132513
# filters
25142514
if self.filters:
25152515
for i, f in enumerate(self.filters):
2516-
items += [("Filter [%s]" % i, repr(f))]
2516+
items += [(f"Filter [{i}]", repr(f))]
25172517

25182518
# compressor
25192519
items += [("Compressor", repr(self.compressor))]
@@ -2530,9 +2530,9 @@ def bytestr(n):
25302530
if self.nbytes_stored > 0:
25312531
items += [
25322532
("No. bytes stored", bytestr(self.nbytes_stored)),
2533-
("Storage ratio", "%.1f" % (self.nbytes / self.nbytes_stored)),
2533+
("Storage ratio", f"{self.nbytes / self.nbytes_stored:.1f}"),
25342534
]
2535-
items += [("Chunks initialized", "{}/{}".format(self.nchunks_initialized, self.nchunks))]
2535+
items += [("Chunks initialized", f"{self.nchunks_initialized}/{self.nchunks}")]
25362536

25372537
return items
25382538

zarr/creation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def _kwargs_compat(compressor, fill_value, kwargs):
282282
compressor = compression
283283

284284
else:
285-
raise ValueError("bad value for compression: %r" % compression)
285+
raise ValueError(f"bad value for compression: {compression!r}")
286286

287287
# handle 'fillvalue'
288288
if "fillvalue" in kwargs:
@@ -292,7 +292,7 @@ def _kwargs_compat(compressor, fill_value, kwargs):
292292

293293
# ignore other keyword arguments
294294
for k in kwargs:
295-
warn("ignoring keyword argument %r" % k)
295+
warn(f"ignoring keyword argument {k!r}")
296296

297297
return compressor, fill_value
298298

zarr/errors.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,7 @@ def __init__(self):
6767

6868

6969
def err_too_many_indices(selection, shape):
70-
raise IndexError(
71-
"too many indices for array; expected {}, got {}".format(len(shape), len(selection))
72-
)
70+
raise IndexError(f"too many indices for array; expected {len(shape)}, got {len(selection)}")
7371

7472

7573
class VindexInvalidSelectionError(_BaseZarrIndexError):

0 commit comments

Comments
 (0)