Skip to content

Commit c19b6c0

Browse files
committed
ZipStore docstring; protect __setitem__ if mode is "r"
1 parent c4f9b83 commit c19b6c0

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

zarr/storage.py

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -677,7 +677,43 @@ def getsize(self, path=None):
677677

678678
# noinspection PyPep8Naming
679679
class ZipStore(MutableMapping):
680-
"""TODO doc me"""
680+
"""Mutable Mapping interface to a Zip file. Keys must be strings,
681+
values must be bytes-like objects.
682+
683+
Parameters
684+
----------
685+
path : string
686+
Location of file.
687+
compression : integer, optional
688+
Compression method to use when writing to the archive.
689+
allowZip64 : bool, optional
690+
If True (the default) will create ZIP files that use the ZIP64
691+
extensions when the zipfile is larger than 2 GiB. If False
692+
will raise an exception when the ZIP file would require ZIP64
693+
extensions.
694+
mode : string, optional
695+
One of 'r' to read an existing file, 'w' to truncate and write a new
696+
file, 'a' to append to an existing file, or 'x' to exclusively create
697+
and write a new file.
698+
699+
Examples
700+
--------
701+
>>> import zarr
702+
>>> store = zarr.ZipStore('example.zip', mode='w')
703+
>>> store['foo'] = b'bar'
704+
>>> store['foo']
705+
b'bar'
706+
>>> store['a/b/c'] = b'xxx'
707+
>>> store['a/b/c']
708+
b'xxx'
709+
>>> sorted(store.keys())
710+
['a/b/c', 'foo']
711+
>>> import zipfile
712+
>>> zf = zipfile.ZipFile('example.zip', mode='r')
713+
>>> sorted(zf.namelist())
714+
['a/b/c', 'foo']
715+
716+
"""
681717

682718
def __init__(self, path, compression=zipfile.ZIP_STORED,
683719
allowZip64=True, mode='a'):
@@ -690,6 +726,7 @@ def __init__(self, path, compression=zipfile.ZIP_STORED,
690726
self.path = path
691727
self.compression = compression
692728
self.allowZip64 = allowZip64
729+
self.mode = mode
693730

694731
def __getitem__(self, key):
695732
with zipfile.ZipFile(self.path) as zf:
@@ -698,7 +735,12 @@ def __getitem__(self, key):
698735

699736
def __setitem__(self, key, value):
700737
value = ensure_bytes(value)
701-
with zipfile.ZipFile(self.path, mode='a',
738+
if self.mode in {'w', 'a', 'x'}:
739+
mode = 'a'
740+
else:
741+
# let zipfile raise an error when trying to write
742+
mode = 'r'
743+
with zipfile.ZipFile(self.path, mode=mode,
702744
compression=self.compression,
703745
allowZip64=self.allowZip64) as zf:
704746
zf.writestr(key, value)

0 commit comments

Comments
 (0)