Check if variable is defined

Stephen Hansen news at myNOSPAM.org
Thu May 17 10:09:44 CEST 2001


Personally, it doesn't seem like a kludge at all.

try:
    variable
except NameError:
    print "Doing stuff since variable is undefined!"

Now, I suspose you could do something like:

if not hasattr(globals(), 'variable'):
    print "Doing stuff since variable is undefined!"

... but that seems more kludgeish, to me. :) It also won't work if variable
was not defined in the global namespace.. and i'm not sure on the best way
to go about testing to see if a variable exists at all up your
namespace-tree except t hrough the try/except clause above.

--S
"Todd A. Jacobs" <nospam at codegnome.org> wrote in message
news:mailman.990085886.31441.python-list at python.org...
> I'm having a lot of trouble doing something that was simple in Perl:
> specifically, I want to create if/else clauses that take action only if a
> particular variable is undefined. How do I check to see if a variable or
> object has already been defined?
>
> If there's no better way, I suppose I could try to catch the exception,
> but that seems like a bit of a kludge, especially if I have to create the
> exception in order to find out what exception the interpreter throws
> first.
>
> --
> Todd A. Jacobs
> CodeGnome Consulting, LTD
>
>
>





More information about the Python-list mailing list