diff options
author | Ganesh Kathiresan <ganesh3597@gmail.com> | 2023-04-06 16:04:33 +0530 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-04-06 12:34:33 +0200 |
commit | be0e502e47b72db8fbd52ab40124fcb07d45936f (patch) | |
tree | d6af8d58891f7c6d573f54edebef03ad529f49c8 /numpy/lib/npyio.py | |
parent | 1307defe4d4bb3d3cbef7adb187c471abf3e904d (diff) | |
download | numpy-be0e502e47b72db8fbd52ab40124fcb07d45936f.tar.gz |
ENH: ``__repr__`` for NpzFile object (#23357)
Improves the repr to include information about the arrays contained, e.g.:
>>> npzfile = np.load('arr.npz')
>>> npzfile
NpzFile 'arr.npz' with keys arr_0, arr_1, arr_2, arr_3, arr_4...
closes #23319
Co-authored-by: Ross Barnowski <rossbar@berkeley.edu>
Diffstat (limited to 'numpy/lib/npyio.py')
-rw-r--r-- | numpy/lib/npyio.py | 16 |
1 files changed, 16 insertions, 0 deletions
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index bfda6804a..f8f2ab7a2 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -167,6 +167,8 @@ class NpzFile(Mapping): >>> npz = np.load(outfile) >>> isinstance(npz, np.lib.npyio.NpzFile) True + >>> npz + NpzFile 'object' with keys x, y >>> sorted(npz.files) ['x', 'y'] >>> npz['x'] # getitem access @@ -178,6 +180,7 @@ class NpzFile(Mapping): # Make __exit__ safe if zipfile_factory raises an exception zip = None fid = None + _MAX_REPR_ARRAY_COUNT = 5 def __init__(self, fid, own_fid=False, allow_pickle=False, pickle_kwargs=None, *, @@ -259,6 +262,19 @@ class NpzFile(Mapping): else: raise KeyError("%s is not a file in the archive" % key) + def __repr__(self): + # Get filename or default to `object` + if isinstance(self.fid, str): + filename = self.fid + else: + filename = getattr(self.fid, "name", "object") + + # Get the name of arrays + array_names = ', '.join(self.files[:self._MAX_REPR_ARRAY_COUNT]) + if len(self.files) > self._MAX_REPR_ARRAY_COUNT: + array_names += "..." + return f"NpzFile {filename!r} with keys: {array_names}" + @set_module('numpy') def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, |