Checking for an "undefined" variable - newbie question

Duncan Booth duncan at
Wed Aug 6 13:27:08 CEST 2003

Dan Rawson <daniel.rawson.take!this!out!> wrote in
news:bgqmce$qk3d1$1 at 

> I have only one (ugly) solution:
> try:
>      variable
> except NameError:
>      ...
> which works, but is a bit clumsy if I just want to know if the thing
> already exists. 

You could check whether the name of the variable is present in 'locals', 
'globals', or 'vars' as appropriate:

>>> 'variable' in vars()

Duncan Booth                                             duncan at
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