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

Bill Mill bill.mill at gmail.com
Wed Mar 9 13:25:02 EST 2005


On 09 Mar 2005 18:13:01 GMT, F. Petitjean <littlejohn.75 at news.proxad.net> wrote:
> 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

but:

>>> d.get('x', (lambda *a: test())())
test called
1

So how is this different than d.get('x', test()) ?

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list