Checking for an "undefined" variable - newbie question

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 6 16:19:48 CEST 2003


Alex Martelli <aleax at aleax.it> wrote in 
news:XL5Ya.40525$cl3.1301474 at news2.tin.it:

> This is the canonical solution.  Personally, I find it quite nice
> that an ugly architecture (such as one based on whether a variable
> is already defined/initialized rather than initializing it at the
> start with a unique value and testing for that!) requires an ugly
> way of expressing it.  Unfortunately there are nicer ones such as
> "if 'variable' not in locals() and 'variable' not in globals():" but
> at least they're verbose and slow:-).

How slow the nicer forms are kind of depends whether or not you expect the 
variable to exist. The canonical solution is very fast if the variable 
exists and the exception isn't thrown, but if the exception is thrown it 
sucks:

>timeit.py "try:" "   variable" "except NameError: pass"
100000 loops, best of 3: 11.3 usec per loop

>timeit.py -s "global variable" -s "variable=0" "try:" "   variable" 
"except NameError: pass"
1000000 loops, best of 3: 0.374 usec per loop

Testing for membership of globals() is pretty fast whether or not the 
variable exists:

>lib\timeit.py "if 'variable' not in globals(): pass"
1000000 loops, best of 3: 0.576 usec per loop

>lib\timeit.py -s "global variable" -s "variable=0" "if 'variable' not in 
globals(): pass"
1000000 loops, best of 3: 0.636 usec per loop

Testing for membership of locals() or vars() is slower than globals() (as 
you would expect), but if the variable doesn't exist it still beats the 
exception block by a long way:

>lib\timeit.py "if 'variable' not in vars(): pass"
1000000 loops, best of 3: 1.44 usec per loop

>lib\timeit.py -s "variable=0" "if 'variable' not in vars(): pass"
1000000 loops, best of 3: 1.75 usec per loop

However, I must say that I agree fully with the point that Alex was really 
making (albeit somewhat obliquely). You shouldn't normally have to do this 
kind of thing at all.

-- 
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