class DictClass2(dict):
A dictionary that allows . attribute read access of its entries.
Assigning an attribute instead of the dictionary entry does not assign
(or create) a dictionary value and separates the attribute value from
the dictionary value permanently (in contrast to DictClass). This may
be useful to let the dictionary entry store the initial value and work
with the attribute value only, to access the current and possibly
changed value.
If neither the attribute nor the dictionary entry exist, an attempted
attribute access raises an AttributeError as to be expected.
By design, this class DOES NOT HAVE INTERACTIVE TAB COMPLETION for attributes derived from the dictionary!?
Implementation detail: this class is less "intrusive" than DictClass
and should be entirely safe from under-the-hood surprises. It only
relies on the behavior of __getattr__: access of a nonexisting
attribute triggers (by Python convention) a call of __getattr__
which is here defined to return the dictionary entry value.
>>> from cma.utilities.utils import DictClass2 >>> d = DictClass2((2 * char, char) for char in 'abcd') >>> list(d) ['aa', 'bb', 'cc', 'dd'] >>> assert d.aa == 'a' and len(d) == 4, (list(d.values()), d.__dict__) >>> d.new = 33 # does not go in the dict >>> assert 'new' not in d and len(d) == 4, (list(d.values()), d.__dict__) >>> d['new'] = 55 >>> assert (d.new, d['new']) == (33, 55) >>> d['nnew'] = 44 >>> assert d.nnew == 44 >>> assert len(d) == 6
| Method | __getattr__ |
called when self.name would raise an attribute error |