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

Bill Mill bill.mill at gmail.com
Wed Mar 9 13:03:47 EST 2005


Dave,

On Wed, 09 Mar 2005 09:45:41 -0800, Dave Opstad <opstad at batnet.com> wrote:
> 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...

There is no short-circuit function like you're asking for, because
it's impossible in python. To pass an argument to the 'get' function,
python evaluates the bigscaryfunction before calling 'get'.

(I believe this means that python doesn't have "lazy evaluation", but
the language lawyers may shoot me down on that. Wikipedia seems to say
that it means python doesn't have "delayed evaluation").

Here are two ways to do what you want:

if 'x' in d: value = d['x']
else: value = bigscaryfunction()

or:

def sget(dict, key, func, *args):
    if key in dict: return key
    else: return func(*args)

sget(d, 'x', bigscaryfunction)

Both methods are untested, but should work with minor modifications.

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list