dict.get(key, default): conditional default evaluation

Gustavo Niemeyer niemeyer at conectiva.com
Mon May 5 10:30:57 EDT 2003


[...]
> I'd prefer if in the latter case A.__init__
> would not be evaluated.  Similar in spirit to
> b in (a and b) not being evaluated if a is False.

You can't change the whole evaluation logic of the language
to satisfy a minor preference for a single method. OTOH, this
behavior is quite easy to achieve:

>>> class lazydict(dict):
...   def lazyget(self, key, default=None):
...     try:
...       return self[key]
...     except KeyError:
...       if default is not None:
...         return eval(default)
...     return None
... 
>>> d = lazydict()
>>> def A():
...   print "I'm A()"
... 
>>> d.get(1, "A()")
'I'm A()'
>>> d[1] = True
>>> d.get(1, "A()")
1

-- 
Gustavo Niemeyer

[ 2AAC 7928 0FBF 0299 5EB5  60E2 2253 B29A 6664 3A0C ]





More information about the Python-list mailing list