Check undefined variable

Aldo Cortesi aldo at nullcube.com
Tue Jul 30 19:05:48 EDT 2002


Thus spake John Hunter (jdhunter at ace.bsd.uchicago.edu):

> >>>>> "Michael" == Michael Grabietz <michael.grabietz at img-online.de> writes:
> 
>     Michael> Hi, how is it possible to check whether a variable 'a' is
>     Michael> undefined or not.
> 
> The namespace is stored in a dictionary that maps variable names to
> values.  You can access the namespace with the functions globals() and
> locals().  Since these return a dictionary, you can use the method
> has_key() to see if the name exists
> 
> >>> globals().has_key('a')
> 0
> >>> locals().has_key('a')
> 0
> >>> a = 1
> >>> globals().has_key('a')
> 1
> >>> locals().has_key('a')
> 1


Unfortunately this idiom doesn't quite work as expected.
Consider the following: 

def foo():
    mung = 1
    def bar():
        print globals(), locals()
        print mung 
    bar()
foo()

With nested scopes, the variable mung is certainly available
within the function bar, yet it is not to be found in either
the globals or locals dictionaries. 

The only complete way to check wether a variable is defined
in a certain scope is to reference it, and catch the
exception. 




Aldo






-- 
Aldo Cortesi
aldo at nullcube.com




More information about the Python-list mailing list