[Tutor] Test if name is defined?
Michael Janssen
Janssen@rz.uni-frankfurt.de
Tue Feb 11 04:26:02 2003
On Mon, 10 Feb 2003, Terry Carroll wrote:
> On Mon, 10 Feb 2003, Sean 'Shaleh' Perry wrote:
> > In a recent enough python:
> >
> > def defined(thing):
> > return (thing in locals()) or (thing in globals())>
> >
> > or, old way:
> >
> > def defined(thing):
> > return (locals().has_key(thing)) or (globals().has_key(thing))
>
> Thanks; but that didn't work.
>
> I tried:
> ========
> def defined(thing):
> return (locals().has_key(thing)) or (globals().has_key(thing))
>
> x = 1
>
> if defined(x):
> print "x is", x
>
> if defined(y):
> print "y is", y
> ========
>
> and got:
>
> ========
> Traceback (most recent call last):
> File "tryit.py", line 10, in ?
> if defined(y):
> NameError: name 'y' is not defined
> ========
The magic is: defined("y") instead of y. Your are looking for a name (or
rather a key in globals() or locals(). Keys of both dictionaries are
strings) not for an object referenced by this name.
cmp lib/built-in-funcs.html for globals() and locals()