Checking for an "undefined" variable - newbie question

Steven Taschuk staschuk at telusplanet.net
Wed Aug 6 14:59:03 CEST 2003


Quoth Dan Rawson:
> How do I check if a variable has been defined??
  [...]
> try:
>      variable
> except NameError:
>      ...

This is the answer to your question.

> If there's a more elegant way to check this, that would be great!

Why do you want to check it in the first place?

In particular, why not initialize your variable to some
out-of-band value (such as None) and test that?  E.g.,

    myvar = None
    # ... code which might set myvar to something else ...
    if myvar is None:
        # ...

-- 
Steven Taschuk                            staschuk at telusplanet.net
Every public frenzy produces legislation purporting to address it.
                                                  (Kinsley's Law)





More information about the Python-list mailing list