Checking for an "undefined" variable - newbie question

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 6 07:27:08 EDT 2003


Dan Rawson <daniel.rawson.take!this!out!@asml.nl> wrote in
news:bgqmce$qk3d1$1 at ID-122008.news.uni-berlin.de: 

> 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()
0

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