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

F. Petitjean littlejohn.75 at news.free.fr
Wed Mar 9 13:13:01 EST 2005


Le Wed, 09 Mar 2005 09:45:41 -0800, Dave Opstad a écrit :
> In this snippet:
> 
> d = {'x': 1}
> value = d.get('x', bigscaryfunction())
> 
> the bigscaryfunction is always called, even though 'x' is a valid key. 
> 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

First (wrong) version :
d.get('z', lambda *a : scary())
<function <lambda> at 0x40598e9c>
> 
> Dave



More information about the Python-list mailing list