Shadow Detection?

Carl J. Van Arsdall cvanarsdall at mvista.com
Tue May 9 16:22:59 EDT 2006


Michael Yanowitz wrote:
> Hello:
>
>   Many times, people are warning things like
> "Don't use 'str' as a variable name as it will shadow the
> built in str function." 
>    Is there some way to determine if a string is already
> defined in some higher scope?
> Maybe something like
> <code>
>
> if isdefined ('str'):
>    print 'str is already defined, please choose another name'
>
>   
You might check out globals() which returns a dictionary of everything:

Python 2.2 (#1, Mar 26 2002, 15:46:04)
[GCC 2.95.3 20010315 (SuSE)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': 
'__main__', '__doc__': None}
 >>> blah = None
 >>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': 
'__main__', '__doc__': None, 'blah': None}

#Taking this a step further, this is a dictionary so you can use the 
has_key method or try to access the dict and catch an exception should 
the key not exist

 >>> if globals().has_key('blah'):
...   print "I have blah"
...
I have blah


-carl


-- 

Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software




More information about the Python-list mailing list