Shadow Detection?

mensanator at aol.com mensanator at aol.com
Tue May 9 16:27:40 EDT 2006


Carl J. Van Arsdall wrote:
> 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

There's also the dir() function:

>>> dir()
['__builtins__', '__doc__', '__name__']


>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError',
'ImportError', 'IndentationError', 'IndexError', 'KeyError',
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None',
'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError',
'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError',
'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',
'TabError', 'True', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning',
'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__',
'__import__', '__name__', 'abs', 'apply', 'basestring', 'bool',
'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']


>>> dir(__name__)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count',
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind',
'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']


>>> dir(__doc__)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__']




More information about the Python-list mailing list