does a variable exist
Wm. King
wjk at wjk.mv.com
Fri Jan 7 18:44:16 EST 2000
Could you do something like:
try:
print x
except NameError:
print "No global or local x"
Just wondering?
Darrell wrote:
> "Dan Grassi" <Dan at Grassi.com> wrote in message
> news:B49BBF60.1373%Dan at Grassi.com...
> > I have forgotten and can not find the function (incantation) that can will
> > determine if a variable currently exisis.
>
> globals() and locals() are your best bet.
>
> >>> import sys
> >>> myVar=123
> >>> sys.modules[__name__].__dict__.keys()
> ['sys', '__doc__', 'myVar', '__name__', '__builtins__']
> >>>
> >>> class A:
> ... classVar=111
> ... def __init__(self):
> ... self._x=1
> ... print self.__dict__.keys()
> ...
> >>> a=A()
> ['_x']
> >>> a.__class__.__dict__.keys()
> ['__init__', '__doc__', 'classVar', '__module__']
> >>>
> >>> def f1(aVar):
> ... print locals().keys()
> ...
> >>> f1(123)
> ['aVar']
> >>>
> >>> print globals().keys()
> ['__doc__', '__name__', 'A', '__builtins__', 'a', 'myVar', 'f1', 'sys']
> >>>
>
> --
> --Darrell
More information about the Python-list
mailing list