<div>You may want to look at the collections.defaultdict class. It takes in a factory function for default values.</div><div><br></div><div>You can also implement your class by overriding the __missing__ method of the dict class, rather than overriding the __getitem__.</div>
<div><br></div><div>Both were added in Python 2.5 according to the documentation.</div><br clear="all">Chris<br>
<br><br><div class="gmail_quote">On Thu, Nov 18, 2010 at 5:45 PM, Phlip <span dir="ltr"><<a href="mailto:phlip2005@gmail.com">phlip2005@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
Pythonistas:<br>
<br>
If everyone likes this post, then the code is a "snippet" for<br>
community edification. Otherwise, it's a question: How to do this kind<br>
of thing better?<br>
<br>
I want a dict() variant that passes these test cases:<br>
<br>
map = Map()<br>
assert not(map.has_key('_default'))<br>
<br>
map = Map(yo='dude')<br>
assert map['yo'] == 'dude'<br>
assert map.yo == 'dude'<br>
assert None == map['whatever']<br>
assert not(map.has_key('_default'))<br>
<br>
map = Map(yo='dude', _default='q')<br>
assert 'q' == map['whatever']<br>
assert not(map.has_key('_default'))<br>
<br>
That's like Bunch, but with a default value. (That makes code with<br>
excess if statements less likely.)<br>
<br>
So here's the implementation:<br>
<br>
def Map(*args, **kwargs):<br>
value = kwargs.get('_default', None)<br>
if kwargs.has_key('_default'): del kwargs['_default']<br>
<br>
class _DefMap(dict):<br>
def __init__(self, *a, **kw):<br>
dict.__init__(self, *a, **kw)<br>
self.__dict__ = self<br>
<br>
def __getitem__(self, key):<br>
if not self.has_key(key): self[key] = value<br>
return dict.__getitem__(self, key)<br>
<br>
return _DefMap(*args, **kwargs)<br>
<br>
--<br>
Phlip<br>
<a href="http://bit.ly/ZeekLand" target="_blank">http://bit.ly/ZeekLand</a><br>
<font color="#888888">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></blockquote></div><br>