pyiron_base.storage.datacontainer.DataContainer#
- class pyiron_base.storage.datacontainer.DataContainer(*args, **kwargs)[source]#
Bases:
DataContainerBase,HasHDF,HasDictMutable sequence with optional keys.
If no argument is given, the constructor creates a new empty DataContainerBase. If specified init maybe a Sequence, Set or Mapping and all recursive occurrences of these are also wrapped by DataContainerBase.
>>> pl = DataContainerBase([3, 2, 1, 0]) >>> pm = DataContainerBase({"foo": 24, "bar": 42})
Access can be like a normal list with integers or optionally with strings as keys.
>>> pl[0] 3 >>> pl[2] 1 >>> pm["foo"] 24
Keys do not have to be present for all elements.
>>> pl2 = DataContainerBase([1,2]) >>> pl2["end"] = 3 >>> pl2 DataContainerBase({0: 1, 1: 2, 'end': 3})
It is also allowed to set an item one past the length of the DataContainerBase, this is then equivalent to appending that element. This allows to use the update method also with other DataContainerBases
>>> pl[len(pl)] = -1 >>> pl DataContainerBase([3, 2, 1, 0, -1]) >>> pl.pop(-1) -1
Where strings are used they may also be used as attributes. Getting keys which clash with methods of DataContainerBase must be done with item access, but setting them works without overwriting the instance methods, but is not recommended for readability.
>>> pm.foo 24 >>> pm.tail = 23 >>> pm DataContainerBase({'foo': 24, 'bar': 42, 'tail': 23})
Keys and indices can be tuples to traverse nested DataContainerBases.
>>> pn = DataContainerBase({"foo": {"bar": [4, 2]}}) >>> pn["foo", "bar"] DataContainerBase([4, 2]) >>> pn["foo", "bar", 0] 4
Using keys with “/” in them is equivalent to the above after splitting the key.
>>> pn["foo/bar"] == pn["foo", "bar"] True >>> pn["foo/bar/0"] == pn["foo", "bar", 0] True
To make that work strings that are only decimal digits are automatically converted to integers before accessing the list and keys are restricted to not only contain digits on initialization.
>>> pl["0"] == pl[0] True >>> DataContainerBase({1: 42}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "datacontainer.py", line 126, in __init__ raise ValueError( ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 1
When initializing from a dict, it may not have integers or decimal strings as keys unless they match their position in the insertion order. This is to avoid ambiguities in the final order of the DataContainerBase.
>>> DataContainerBase({0: "foo", 1: "bar", 2: 42}) DataContainerBase(['foo', 'bar', 42]) >>> DataContainerBase({0: "foo", 2: 42, 1: "bar"}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "datacontainer.py", line 132, in __init__ raise ValueError( ValueError: keys in initializer must not be int or str of decimal digits or in correct order, is 2
Using keys is completely optional, DataContainerBase can always be treated as a list, with the exception that iter() iterates of the keys and indices. This is to correctly implement the MutableMapping protocol, to convert to a normal list and discard the keys use values().
>>> pm[0] 24 >>> pn["0/0/1"] 2 >>> list(pl) [0, 1, 2, 3] >>> list(pl.values()) [3, 2, 1, 0] >>> list(pl.keys()) [0, 1, 2, 3]
Implements
HasGroups. Groups are nested data containers and nodes are everything else.>>> p = DataContainerBase({"a": 42, "b": [0, 1, 2]}) >>> p.list_groups() ['b'] >>> p.list_nodes() ['a']
Attention
Subclasses beware!
DataContainerBase require some careful treatment when creating subclasses.
1. Since DataContainerBases are expected to recursively instantiate themselves subclasses need to keep their __init__ compatible to the base class. That means being able to be instantiated without arguments, if arguments are given the first one (or `init) has to accept a Mapping or Iterable. Additional arguments may be added, but must be after init and must have a default.
2. Creating new instance attributes that don’t live in the container itself is possible, but you need to use object.__setattr__ the first time you define that attribute. Afterwards using normal assignment syntax works.
3. Subclasses should always be thought of as general data structures, if you want to subclass to have access to the HDF5 functionality or the way the DataContainerBase is shown in jupyter notebooks, but only have a fixed number of attributes it is better to create a new class that has an DataContainerBase as an attribute and dispatch to the
DataContainerBase.from_hdf(),DataContainerBase.to_hdf()andDataContainerBase._repr_json_()methods.A few examples for subclasses
>>> class ExtendedContainer(DataContainerBase): ... def __init__(self, init=None, my_fancy_field=42, table_name=None): ... super().__init__(init=init, table_name=table_name) ... object.__setattr__(self, "my_fancy_field", my_fancy_field)
After defining it once like this you can access my_fancy_field as a normal attribute, but it will not be stored in the container itself and will not be stored in HDF5.
>>> e = ExtendedContainer({'foo': 1, 'bar': 5}, my_fancy_field=23) >>> e.my_fancy_field 23 >>> e ExtendedContainer({'foo': 1, 'bar': 5}) >>> e.my_fancy_field = 42 >>> e.my_fancy_field 42 >>> e ExtendedContainer({'foo': 1, 'bar': 5})
Be aware the
DataContainerBaseand its subclasses are recursive data structures, i.e. your fancy attribute will be available also on sub groups.>>> g = e.create_group('sub') >>> g.fnord = 23 >>> g.my_fancy_field 42 >>> e ExtendedContainer({'foo': 1, 'bar': 5, 'sub': ExtendedContainer({'fnord': 23})})
For that reason most of time you’ll actually want a class that uses a DataContainerBase for storage, but doesn’t derive from it.
>>> from pyiron_base.interfaces.object import HasStorage >>> class FancyClass(HasStorage): ... def __init__(self, foo): ... super().__init__() ... self.storage.foo = foo ... ... @property ... def foo(self): ... return self.storage.foo ... ... @foo.setter ... def foo(self, val): ... self.storage.foo = val ... ... def _repr_json_(self): ... return self.storage._repr_json_()
If instantiated with the argument lazy=True, data read from HDF5 later via :method:`.from_hdf` are not actually read, but only earmarked to be read later when actually accessed via
HDFStub. This is largely transparent, i.e. when accessing an earmarked value it will automatically be loaded and this loaded value is stored in container. The only difference is in the string representation of the container, values not read yet appear as ‘HDFStub(…)’ in the output.Attention
Subclasses beware! 1. To allow lazy loading sub classes must accept a lazy keyword argument and pass it to super().__init__.
- __init__(init=None, table_name=None, lazy=False, wrap_blacklist=(), lock_method='warning')[source]#
Create new container.
- Parameters:
init (Sequence, Mapping) – initial data for the container, nested occurances of Sequence and Mapping are translated to nested containers
table_name (str) – default name of the data container in HDF5
lazy (bool) – if True, use
HDFStubto load values lazily from HDF5wrap_blacklist (tuple of types) – any values in init that are instances of the given types are not wrapped in
DataContainerBase
Methods
__init__([init, table_name, lazy, ...])Create new container.
append(val)Add new value to the container without a key.
clear()Remove all items from DataContainerBase.
copy()Returns deep copy of it self.
create_group(name)Add a new empty subcontainer under the given key.
extend(vals)Append vals to the end of this DataContainerBase.
from_dict(obj_dict[, version])Populate the object from the serialized object.
from_hdf(hdf[, group_name])Read object to HDF.
from_hdf_args(hdf)Read arguments for instance creation from HDF5 file.
get(key[, default, create])If
keyexists, behave as generic, if not call create_group.groups()Iterate over keys to nested containers.
has_keys()Check if the container has keys set or not.
insert(index, val[, key])Add a new element to the container at the specified position, with an optional key.
instantiate(obj_dict[, version])Create a blank instance of this class.
items()keys()list_all()Returns dictionary of :method:`.list_groups()` and :method:`.list_nodes()`.
Return a list of names of all nested groups.
Return a list of names of all nested nodes.
lock([method])Set
read_only.mark(index, key)Add a key to an existing item at index.
nodes()Iterator over keys to terminal nodes.
pop(k[,d])value.
popitem()as a 2-tuple; but raise KeyError if D is empty.
read(file_name[, wrap])Parse file as dictionary and add its keys to this container.
rewrite_hdf(hdf[, group_name])Update the HDF representation.
search(key[, stop_on_first_hit])Search for
keyin the Container hierarchy.setdefault(k[,d])to_builtin([stringify])Convert the container back to builtin dict's and list's recursively.
to_dict()Reduce the object to a dictionary.
to_hdf(hdf[, group_name])Write object to HDF.
unlocked()Unlock the object temporarily.
update(init[, wrap, blacklist])Add all elements or key-value pairs from init to this container.
values()write(file_name)Writes the DataContainerBase to a text file.
Attributes
False if the object can currently be written to
- append(val)#
Add new value to the container without a key.
- Parameters:
val – new element
- clear()#
Remove all items from DataContainerBase.
- copy()[source]#
Returns deep copy of it self. A shallow copy can be obtained via the copy module.
- Returns:
deep copy of itself
- Return type:
>>> pl = DataContainer([[1,2,3]]) >>> pl.copy() == pl True >>> pl.copy() is pl False >>> all(a is not b for a, b in zip(pl.copy().values(), pl.values())) True
- create_group(name)#
Add a new empty subcontainer under the given key.
- Parameters:
name (str) – key under which to store the new subcontainer in this container
- Returns:
the newly created subcontainer
- Return type:
- Raises:
ValueError – name already exists in container and is not a sub container
>>> pl = DataContainerBase({}) >>> pl.create_group("group_name") DataContainerBase([]) >>> list(pl.group_name) []
- extend(vals)#
Append vals to the end of this DataContainerBase.
- Parameters:
vals (Sequence) – any python sequence to draw new elements from
- from_dict(obj_dict: dict, version: str = None)#
Populate the object from the serialized object.
- Parameters:
obj_dict (dict) – data previously returned from
to_dict()version (str) – version tag written together with the data
- from_hdf(hdf: ProjectHDFio, group_name: str = None)#
Read object to HDF.
If group_name is given descend into subgroup in hdf first.
- Parameters:
hdf (
ProjectHDFio) – HDF group to read fromgroup_name (str, optional) – name of subgroup
- classmethod from_hdf_args(hdf: ProjectHDFio) dict#
Read arguments for instance creation from HDF5 file.
- Parameters:
hdf (ProjectHDFio) – HDF5 group object
- Returns:
arguments that can be **kwarg-passed to cls().
- Return type:
dict
- get(key, default=None, create=False)#
If
keyexists, behave as generic, if not call create_group.- Parameters:
key (str) – key to search
default (optional) – return this instead if nothing found
create (bool, optional) – create empty container at key if nothing found
- Raises:
IndexError – if key is not in the container and neither
defaultnotcreate` are give –
- Returns:
element at
keyor new empty subcontainer- Return type:
object
- groups()#
Iterate over keys to nested containers.
- Returns:
list of all keys to elements of
DataContainerBase.- Return type:
list
- has_keys()#
Check if the container has keys set or not.
- Returns:
True if there is at least one key set
- Return type:
bool
- insert(index, val, key=None)#
Add a new element to the container at the specified position, with an optional key. If the key is already in the container it will be updated to point to the new element at the new index. If index is larger than container, append instead.
- Parameters:
index (int) – place val after this element
val – new element to add
key (str, optional) – optional key to mark the new element
- classmethod instantiate(obj_dict: dict, version: str = None) Self#
Create a blank instance of this class.
This can be used when some values are already necessary for the objects __init__.
- Parameters:
obj_dict (dict) – data previously returned from
to_dict()version (str) – version tag written together with the data
- Returns:
a blank instance of the object that is sufficiently initialized to call
_from_dict()on it- Return type:
object
- items() a set-like object providing a view on D's items#
- keys() a set-like object providing a view on D's keys#
- list_all()#
Returns dictionary of :method:`.list_groups()` and :method:`.list_nodes()`.
- Returns:
- results of :method:`.list_groups() under the key "groups"; results of :method:`.list_nodes()` und the
key “nodes”
- Return type:
dict
- list_groups()#
Return a list of names of all nested groups.
- Returns:
group names
- Return type:
list of str
- list_nodes()#
Return a list of names of all nested nodes.
- Returns:
node names
- Return type:
list of str
- lock(method: Literal['error', 'warning'] | None = None)#
Set
read_only.Objects may be safely locked multiple times without further effect.
- Parameters:
method (str, either "error" or "warning") – if “error” raise an
Lockedexception if modification is attempted; if “warning” raise aLockedWarningwarning; default is “error” or the value passed to the constructor.- Raises:
ValueError – if method is not an allowed value
- mark(index, key)#
Add a key to an existing item at index. If key already exists, it is overwritten.
- Parameters:
index (int) – index of the existing element to mark
key (str) – key for the existing element
- Raises:
IndexError – if index > len(self)
>>> pl = DataContainerBase([42]) >>> pl.mark(0, "head") >>> pl.head == 42 True
- nodes()#
Iterator over keys to terminal nodes.
- Returns:
list of keys to normal values.
- Return type:
list
- pop(k[, d]) v, remove specified key and return the corresponding#
value. If key is not found, d is returned if given, otherwise KeyError is raised.
- popitem() (k, v), remove and return some (key, value) pair#
as a 2-tuple; but raise KeyError if D is empty.
- read(file_name, wrap=True)#
Parse file as dictionary and add its keys to this container.
For supported file types, see
fileio.read().Errors during reading of the files generate a warning, but leave the container unchanged.
- Parameters:
file_name (str) – path to the input file
wrap (bool)
- Raises:
ValueError – if file extension doesn’t match one of the supported ones
- property read_only: bool#
False if the object can currently be written to
Setting this value will trigger
_on_lock()and_on_unlock()if it changes.- Type:
bool
- rewrite_hdf(hdf: ProjectHDFio, group_name: str = None)#
Update the HDF representation.
If an object is read from an older layout, this will remove the old data and rewrite it in the newest layout.
- Parameters:
hdf (
ProjectHDFio) – HDF group to read/writegroup_name (str, optional) – name of subgroup
- search(key, stop_on_first_hit=True)#
Search for
keyin the Container hierarchy.This should be used if there is only one such item in the hierarchy.
If stop_on_first_hit is True the first item found is taken. Otherwise, a ValueError is raised if the key appears multiple times.
- Parameters:
key (str) – the key to look for
stop_on_first_hit (bool) – whether to stop on the first hit
- Raises:
TypeError – if key is not str
KeyError – if key is not found
ValueError – if stop_on_first_hit is False and key is found twice
- Returns:
element at
key- Return type:
object
- setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
- to_builtin(stringify=False)[source]#
Convert the container back to builtin dict’s and list’s recursively.
- Parameters:
stringify (bool, optional) – convert all non-recursive elements to str
- to_dict() dict#
Reduce the object to a dictionary.
- Returns:
serialized state of this object
- Return type:
dict
- to_hdf(hdf: ProjectHDFio, group_name: str = None)#
Write object to HDF.
If group_name is given create a subgroup in hdf first.
- Parameters:
hdf (
ProjectHDFio) – HDF group to write togroup_name (str, optional) – name of subgroup
- unlocked() _UnlockContext#
Unlock the object temporarily.
Context manager returns this object again and relocks it after the with statement finished.
Note
lock() vs. unlocked()
There is a small asymmetry between these two methods.
lock()can only be done once (meaningfully), whileunlocked()is a context manager and can be called multiple times.
- update(init, wrap=False, blacklist=(), **kwargs)#
Add all elements or key-value pairs from init to this container. If wrap is not given, behaves as the generic method.
- Parameters:
init (Sequence, Set, Mapping) – container to draw new elements from
wrap (bool) – if True wrap all encountered Sequences and Mappings in
DataContainerBaserecursivelyblacklist (list of types) – when wrap is True, don’t wrap these types even if they’re instances of Sequence or Mapping
**kwargs – update from this mapping as well
- values() an object providing a view on D's values#
- write(file_name)#
Writes the DataContainerBase to a text file.
For supported file types, see
fileio.write().- Parameters:
file_name (str) – the name of the file to be writen to.