libb.attrdict
- class attrdict[source]
Bases:
dictA dictionary subclass that allows attribute-style access.
This is a dictionary that allows access to its keys as attributes (using dot notation) in addition to standard dictionary access methods.
Basic Usage:
>>> import copy >>> d = attrdict(x=10, y='foo') >>> d.x 10 >>> d['x'] 10 >>> d.y = 'baa' >>> d['y'] 'baa' >>> g = d.copy() >>> g.x = 11 >>> d.x 10 >>> d.z = 1 >>> d.z 1 >>> 'x' in d True >>> 'w' in d False >>> d.get('x') 10 >>> d.get('w')
Deep Copy Behavior:
>>> tricky = [d, g] >>> tricky2 = copy.copy(tricky) >>> tricky2[1].x 11 >>> tricky2[1].x = 12 >>> tricky[1].x 12 >>> righty = copy.deepcopy(tricky) >>> righty[1].x 12 >>> righty[1].x = 13 >>> tricky[1].x 12
Access Methods (handles
obj.get('attr'),obj['attr'], andobj.attr):>>> class A(attrdict): ... @property ... def x(self): ... return 1 >>> a = A() >>> a['x'] == a.x == a.get('x') True >>> a.get('b') >>> a['b'] Traceback (most recent call last): ... KeyError: 'b' >>> a.b Traceback (most recent call last): ... AttributeError: b
A method name is not data, so the fallback stops before the names this class defines. Store the key to read one:
>>> a['keys'] Traceback (most recent call last): ... KeyError: 'keys' >>> attrdict(keys=3)['keys'] 3
- __getitem__(attrname)[source]
Read a key, or a subclass attribute of that name.
- Parameters:
attrname (str) – Key to read. A stored key always wins.
- Returns:
The stored value, else the attribute of that name.
- Return type:
Any
- Raises:
KeyError – The name is neither a key, nor an attribute the subclass declares.
Notes
The attribute fallback is what makes a declared property read the same three ways: obj[‘x’], obj.x and obj.get(‘x’).
It stops at this class’s own method names, which are data to nobody. That stop is what keeps name in obj, obj[name] and obj.get(name, default) answering alike for every name.
- copy(**kwargs)[source]
Shallow-copy into the same class, then apply kwargs as overrides.
- Parameters:
**kwargs – Keys written over the copy after it is made.
- Returns:
A new instance of type(self), never of attrdict itself.
- Return type:
Notes
The class carries the read behavior, so a copy has to keep it: a lazydict copied into an attrdict hands back a stored callable instead of resolving it.
- classmethod fromkeys(iterable, value=None)[source]
Create a new attrdict with keys from iterable and values set to value.