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

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Wed Mar 9 14:46:00 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...

Well, if the dict only contains ints, here is a dirty hack (but don't
use it instead of the try/except approach):

class Littletinyproxy:
    def __int__(self):
        return bigscaryfunction()

d = dict(x=1)
value = int(d.get('x', Littletinyproxy()))


Reinhold



More information about the Python-list mailing list