slow try statements in python?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Feb 20 04:44:36 EST 2003


sjmachin at lexicon.net (John Machin) wrote in 
news:c76ff6fc.0302191309.4db8c0d9 at posting.google.com:

>> The second method takes 0.81 seconds whether or not the key is found.
> 
>> def testHasAttr(aDict):
>>     if hasattr(aDict, "xyz"):
>>         a = aDict["xyz"]
>>     else:
>>         a = "Not found"
>>     return a
>> 
> 

Ok, the non-brain-failure version of what I intended for this function is:

def testIn(aDict):
    if "xyz" in aDict:
        a = aDict["xyz"]
    else:
        a = "Not found"
    return a

Interestingly this version is somewhat faster than the 'get' version. (0.33 
for a hit, 0.30 for a miss). This isn't what I expected as it accesses the 
dictionary twice, and I would have thought the single access with 'get' 
should be faster. Maybe its the method lookup?

The above times are all for Python 2.2, the (not current) copy of Python 
2.3 on my machine gives slightly faster times for everything but the 
relative timings are all the same (exception hit and 'in' miss are equally 
fast, then 'in' hit, then 'get', then the exception miss a long way 
behind).

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list