Newbie Variable Definition Question

Tim Peters tim_one at email.msn.com
Wed Dec 15 02:48:42 EST 1999


[Andrew N. McGuire]
> ...
> I was wondering if there was a way to check if a variable is
> assigned by referencing its name in python, even if there is a
> chance that it is not defined....
> All my attempts lead to NameError, perhaps this can be used,
> but I have not figured out how to keep the script from stopping
> after the NameError error.

As has been said, wrapping in a "try:/except NameError:" block is a reliable
way to do this.

As has not been said, take the opportunity to learn a better of doing this
stuff.  It's a Real Language; shell hideousisms can be left behind with
obscene glee!  For example, Python supports default arguments, default
values for getattr, default dict lookup values via dict.get(thing, default),
and so on.  Testing for name definition is a bad old brittle habit.

neutrally y'rs  - tim






More information about the Python-list mailing list