Is there a short-circuiting dictionary "get" method?

Kent Johnson kent37 at tds.net
Wed Mar 9 13:36:06 EST 2005


F. Petitjean wrote:
> Le Wed, 09 Mar 2005 09:45:41 -0800, Dave Opstad a écrit :
>>Is there a "short-circuit" version of get that doesn't evaluate the 
>>second argument if the first is a valid key? For now I'll code around 
>>it, but this behavior surprised me a bit...
> 
> def scary():
>     print "scary called"
>     return 22
> 
> d = dict(x=1)
> d.get('x', lambda *a : scary())
> # print 1
> d.get('z', (lambda *a : scary())())
> scary called
> 22

So you have to change the code at the point of call depending on whether the requested value is in 
the dict? ;)

If you can get this to work I'm sure we can find other applications for such 'smart code' :-)

Kent



More information about the Python-list mailing list