Skip to content

Commit b04d212

Browse files
Change occurrences of % and format() to f-strings
1 parent 4944e66 commit b04d212

18 files changed

+180
-234
lines changed

docs/release.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ Release notes
1818
Unreleased
1919
----------
2020

21+
Maintenance
22+
~~~~~~~~~~~
23+
24+
* Change occurrences of % and format() to f-strings.
25+
By :user:`Dimitri Papadopoulos Orfanos <DimitriPapadopoulos>` :issue:`1423`.
26+
2127
.. _release_2.16.1:
2228

2329
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"keys 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 & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ def save_group(store: StoreLike, *args, zarr_version=None, path=None, **kwargs):
257257
try:
258258
grp = _create_group(_store, path=path, overwrite=True, zarr_version=zarr_version)
259259
for i, arr in enumerate(args):
260-
k = "arr_{}".format(i)
260+
k = f"arr_{i}"
261261
grp.create_dataset(k, data=arr, overwrite=True, zarr_version=zarr_version)
262262
for k, arr in kwargs.items():
263263
grp.create_dataset(k, data=arr, overwrite=True, zarr_version=zarr_version)
@@ -497,7 +497,7 @@ def __init__(self, log):
497497
self.log_file = log
498498
else:
499499
raise TypeError(
500-
"log must be a callable function, file path or " "file-like object, found %r" % log
500+
f"log must be a callable function, file path or file-like object, found {log!r}"
501501
)
502502

503503
def __enter__(self):
@@ -524,9 +524,9 @@ def _log_copy_summary(log, dry_run, n_copied, n_skipped, n_bytes_copied):
524524
message = "dry run: "
525525
else:
526526
message = "all done: "
527-
message += "{:,} copied, {:,} skipped".format(n_copied, n_skipped)
527+
message += f"{n_copied:,} copied, {n_skipped:,} skipped"
528528
if not dry_run:
529-
message += ", {:,} bytes copied".format(n_bytes_copied)
529+
message += f", {n_bytes_copied:,} bytes copied"
530530
log(message)
531531

532532

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

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

727725
# take action
728726
if do_copy:
729-
log("copy {}".format(descr))
727+
log(f"copy {descr}")
730728
if not dry_run:
731729
data = source[source_key]
732730
n_bytes_copied += buffer_size(data)
733731
dest[dest_key] = data
734732
n_copied += 1
735733
else:
736-
log("skip {}".format(descr))
734+
log(f"skip {descr}")
737735
n_skipped += 1
738736

739737
# log a final message with a summary of what happened
@@ -744,7 +742,7 @@ def copy_store(
744742

745743
def _check_dest_is_group(dest):
746744
if not hasattr(dest, "create_dataset"):
747-
raise ValueError("dest must be a group, got {!r}".format(dest))
745+
raise ValueError(f"dest must be a group, got {dest!r}")
748746

749747

750748
def copy(
@@ -756,7 +754,7 @@ def copy(
756754
log=None,
757755
if_exists="raise",
758756
dry_run=False,
759-
**create_kws
757+
**create_kws,
760758
):
761759
"""Copy the `source` array or group into the `dest` group.
762760
@@ -889,7 +887,7 @@ def copy(
889887
without_attrs=without_attrs,
890888
if_exists=if_exists,
891889
dry_run=dry_run,
892-
**create_kws
890+
**create_kws,
893891
)
894892

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

920916
# determine name to copy to
921917
if name is None:
@@ -936,7 +932,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
936932
if exists:
937933
if if_exists == "raise":
938934
raise CopyError(
939-
"an object {!r} already exists in destination " "{!r}".format(name, dest.name)
935+
f"an object {name!r} already exists in destination " "{dest.name!r}"
940936
)
941937
elif if_exists == "skip":
942938
do_copy = False
@@ -949,7 +945,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
949945
if do_copy:
950946

951947
# log a message about what we're going to do
952-
log("copy {} {} {}".format(source.name, source.shape, source.dtype))
948+
log(f"copy {source.name} {source.shape} {source.dtype}")
953949

954950
if not dry_run:
955951

@@ -1018,7 +1014,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10181014
n_copied += 1
10191015

10201016
else:
1021-
log("skip {} {} {}".format(source.name, source.shape, source.dtype))
1017+
log(f"skip {source.name} {source.shape} {source.dtype}")
10221018
n_skipped += 1
10231019

10241020
elif root or not shallow:
@@ -1029,17 +1025,15 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10291025
exists_array = dest is not None and name in dest and hasattr(dest[name], "shape")
10301026
if exists_array:
10311027
if if_exists == "raise":
1032-
raise CopyError(
1033-
"an array {!r} already exists in destination " "{!r}".format(name, dest.name)
1034-
)
1028+
raise CopyError(f"an array {name!r} already exists in destination {dest.name!r}")
10351029
elif if_exists == "skip":
10361030
do_copy = False
10371031

10381032
# take action
10391033
if do_copy:
10401034

10411035
# log action
1042-
log("copy {}".format(source.name))
1036+
log(f"copy {source.name}")
10431037

10441038
if not dry_run:
10451039

@@ -1075,7 +1069,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10751069
without_attrs=without_attrs,
10761070
if_exists=if_exists,
10771071
dry_run=dry_run,
1078-
**create_kws
1072+
**create_kws,
10791073
)
10801074
n_copied += c
10811075
n_skipped += s
@@ -1084,7 +1078,7 @@ def _copy(log, source, dest, name, root, shallow, without_attrs, if_exists, dry_
10841078
n_copied += 1
10851079

10861080
else:
1087-
log("skip {}".format(source.name))
1081+
log(f"skip {source.name}")
10881082
n_skipped += 1
10891083

10901084
return n_copied, n_skipped, n_bytes_copied
@@ -1098,7 +1092,7 @@ def copy_all(
10981092
log=None,
10991093
if_exists="raise",
11001094
dry_run=False,
1101-
**create_kws
1095+
**create_kws,
11021096
):
11031097
"""Copy all children of the `source` group into the `dest` group.
11041098
@@ -1200,7 +1194,7 @@ def copy_all(
12001194
without_attrs=without_attrs,
12011195
if_exists=if_exists,
12021196
dry_run=dry_run,
1203-
**create_kws
1197+
**create_kws,
12041198
)
12051199
n_copied += c
12061200
n_skipped += s
@@ -1335,7 +1329,7 @@ def open_consolidated(store: StoreLike, metadata_key=".zmetadata", mode="r+", **
13351329
store, storage_options=kwargs.get("storage_options"), mode=mode, zarr_version=zarr_version
13361330
)
13371331
if mode not in {"r", "r+"}:
1338-
raise ValueError("invalid mode, expected either 'r' or 'r+'; found {!r}".format(mode))
1332+
raise ValueError(f"invalid mode, expected either 'r' or 'r+'; found {mode!r}")
13391333

13401334
path = kwargs.pop("path", None)
13411335
if store._store_version == 2:

zarr/core.py

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

24542454
def __repr__(self):
24552455
t = type(self)
2456-
r = "<{}.{}".format(t.__module__, t.__name__)
2456+
r = f"<{t.__module__}.{t.__name__}"
24572457
if self.name:
2458-
r += " %r" % self.name
2459-
r += " %s" % str(self.shape)
2460-
r += " %s" % self.dtype
2458+
r += f" {self.name!r}"
2459+
r += f" {str(self.shape)}"
2460+
r += f" {self.dtype}"
24612461
if self._read_only:
24622462
r += " read-only"
24632463
r += ">"
@@ -2493,11 +2493,11 @@ def info_items(self):
24932493

24942494
def _info_items_nosync(self):
24952495
def typestr(o):
2496-
return "{}.{}".format(type(o).__module__, type(o).__name__)
2496+
return f"{type(o).__module__}.{type(o).__name__}"
24972497

24982498
def bytestr(n):
24992499
if n > 2**10:
2500-
return "{} ({})".format(n, human_readable_size(n))
2500+
return f"{n} ({human_readable_size(n)})"
25012501
else:
25022502
return str(n)
25032503

@@ -2508,7 +2508,7 @@ def bytestr(n):
25082508
items += [("Name", self.name)]
25092509
items += [
25102510
("Type", typestr(self)),
2511-
("Data type", "%s" % self.dtype),
2511+
("Data type", str(self.dtype)),
25122512
("Shape", str(self.shape)),
25132513
("Chunk shape", str(self.chunks)),
25142514
("Order", self.order),
@@ -2518,7 +2518,7 @@ def bytestr(n):
25182518
# filters
25192519
if self.filters:
25202520
for i, f in enumerate(self.filters):
2521-
items += [("Filter [%s]" % i, repr(f))]
2521+
items += [(f"Filter [{i}]", repr(f))]
25222522

25232523
# compressor
25242524
items += [("Compressor", repr(self.compressor))]
@@ -2535,9 +2535,9 @@ def bytestr(n):
25352535
if self.nbytes_stored > 0:
25362536
items += [
25372537
("No. bytes stored", bytestr(self.nbytes_stored)),
2538-
("Storage ratio", "%.1f" % (self.nbytes / self.nbytes_stored)),
2538+
("Storage ratio", f"{self.nbytes / self.nbytes_stored:.1f}"),
25392539
]
2540-
items += [("Chunks initialized", "{}/{}".format(self.nchunks_initialized, self.nchunks))]
2540+
items += [("Chunks initialized", f"{self.nchunks_initialized}/{self.nchunks}")]
25412541

25422542
return items
25432543

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 {shape}, got {selection}")
7371

7472

7573
class VindexInvalidSelectionError(_BaseZarrIndexError):

0 commit comments

Comments
 (0)