Is there a short-circuiting dictionary "get" method?
Peter Hansen
peter at engcorp.com
Wed Mar 9 12:48:46 EST 2005
Dave Opstad 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...
try:
value = d['x']
except KeyError:
value = bigscaryfunction()
get() is just a method, and arguments to methods are always
evaluated before being passed to the method, so the short
answer is "no, there is no 'version' of get() that will do
what you want".
-Peter
More information about the Python-list
mailing list