trouble testing for existance of variable

Fredrik Lundh fredrik at pythonware.com
Tue Mar 12 17:25:11 EST 2002


googlePoster wrote:
> python gurus:
>
> if I want to know if a variable exists before
> testing it, what do I do?

gurus don't write code that do stuff like that, but
never mind...

>    if locals().has_key("colors_name")

try:
    colors_name
except NameError:
    # doesn't exist
else:
    # does exist; do something

or:

try:
    # does it exist?
    colors_name
except NameError:
    colors_name = None
    # now it does

...

if colors_name:
    # do something

(etc)

</F>





More information about the Python-list mailing list