81. mydict
—¶
CDict is a Dict with lookup cascading into the next level Dict’s if the key is not found in the CDict itself.
(C) 2005,2008 Benedict Verhegghe Distributed under the GNU GPL version 3 or later
81.1. Classes defined in module mydict¶
-
class
mydict.
Dict
(data={}, default=None)[source]¶ A Python dictionary with default values and attribute syntax.
Dict
is functionally nearly equivalent with the builtin Pythondict
, but provides the following extras:- Items can be accessed with attribute syntax as well as dictionary
syntax. Thus, if
C
is aDict
,C['foo']
andC.foo
are equivalent. This works as well for accessing values as for setting values. In the following, the terms key or attribute therefore have the same meaning. - Lookup of a nonexisting key/attribute does not automatically raise an
error, but calls a
_default_
lookup method which can be set by the user. The default is to raise a KeyError( but an alternative is to return None or some other default value.
There are a few caveats though:
Keys that are also attributes of the builtin dict type, can not be used with the attribute syntax to get values from the Dict. You should use the dictionary syntax to access these items. It is possible to set such keys as attributes. Thus the following will work:
C['get'] = 'foo' C.get = 'foo' print(C['get'])
but this will not:
print(C.get)
This is done so because we want all the dict attributes to be available with their normal binding. Thus,
print(C.get('get'))
will print
foo
To avoid name clashes with user defines, many Python internal names start and end with ‘__’. The user should avoid such names. The Python dict has the following attributes not enclosed between ‘__’, so these are the ones to watch out for: ‘clear’, ‘copy’, ‘fromkeys’, ‘get’, ‘items’, ‘iteritems’, ‘iterkeys’, ‘itervalues’, ‘keys’, ‘pop’, ‘popitem’, ‘setdefault’, ‘update’, ‘values’, viewitems, viewkeys, viewvalues.
-
update
(data={}, **kargs)[source]¶ Add a dictionary to the Dict object.
The data can be a dict or Dict type object.
- Items can be accessed with attribute syntax as well as dictionary
syntax. Thus, if
-
class
mydict.
CDict
(data={}, default=<function returnNone>)[source]¶ A cascading Dict: properties not in Dict are searched in all Dicts.
This is equivalent to the Dict class, except that if a key is not found and the CDict has items with values that are themselves instances of Dict or CDict, the key will be looked up in those Dicts as well.
As you expect, this will make the lookup cascade into all lower levels of CDict’s. The cascade will stop if you use a Dict. There is no way to guarantee in which order the (Cascading)Dict’s are visited, so if multiple Dicts on the same level hold the same key, you should know yourself what you are doing.
Example:
>>> C = CDict({'a':'aa','d':{'a':'aaa','b':'bbb'}}) >>> print(C['a']) aa >>> print(C['d']) {'a': 'aaa', 'b': 'bbb'} >>> print(C['b']) bbb