[Tutor] Test if name is defined?
Terry Carroll
carroll@tjc.com
Tue Feb 11 02:13:03 2003
On Mon, 10 Feb 2003, Sean 'Shaleh' Perry wrote:
> On Monday 10 February 2003 21:26, Terry Carroll wrote:
> > Is there a way to test to see if a variable is defined other than with the
> > exception system?
> >
>
> 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
========
Same error with both versions.
--
Terry Carroll | "To have this rare opportunity
Santa Clara, CA | is a rare opportunity."
carroll@tjc.com | - Houston Rockets' Yao Ming, on being named
Modell delendus est | starting center for the 2003 NBA All-Star Game