default behavior

Christian Heimes lists at cheimes.de
Sat Jul 31 11:08:11 EDT 2010


Am 30.07.2010 14:34, schrieb wheres pythonmonks:
> I was hoping not to do that -- e.g., actually reuse the same
> underlying data.  Maybe dict(x), where x is a defaultdict is smart?  I
> agree that a defaultdict is safe to pass to most routines, but I guess
> I could imagine that a try/except block is used in a bit of code where
> on the key exception (when the value is absent)  populates the value
> with a random number.  In that application, a defaultdict would have
> no random values.

defaultdict not only behaves like an ordinary dict except for missing
keys, it's also a subclass of Python's builtin dict type. You are able
to use a defaultdict just like a normal dict all over Python. You can
also provide your own custom implementation of a defaultdict that fits
your needs. All you have to do is subclass dict and implement a
__missing__ method. See
http://docs.python.org/library/stdtypes.html?highlight=__missing__#mapping-types-dict

Christian




More information about the Python-list mailing list