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

Skip Montanaro skip at pobox.com
Wed Mar 9 14:02:03 EST 2005


    Dave> In this snippet:
    Dave> d = {'x': 1}
    Dave> value = d.get('x', bigscaryfunction())

    Dave> the bigscaryfunction is always called, even though 'x' is a valid
    Dave> key. 

I sometimes use

    value = d.get('x') or bsf()

Of course, this bsf() will get called if d['x'] evaluates to false, not just
None, so it won't work in all situations.  It may help often enough to be
useful though.

Skip



More information about the Python-list mailing list