Test to see if variable exists

L

lamar_air

I need an if statement to test if a variable exists in a pyton script

eg. if var1 exists:
do this
else:
do this
 
J

John Hunter

lamar> I need an if statement to test if a variable exists in a
lamar> pyton script eg. if var1 exists: do this else: do this --


try: x
except NameError:
# x doesn't exist, do something
else:
# x exists, do something else
 
G

Gabriel Cooper

lamar_air said:
I need an if statement to test if a variable exists in a pyton script

eg. if var1 exists:
do this
else:
do this
If it's in a dictionary you can do this: var1.get('key','not found')

( just learned that all of 2 minutes ago ;] )
 
?

=?iso-8859-1?q?Fran=E7ois_Pinard?=

[Graham Breed]
locals().has_key('var1')

The above could also be written:

'var1' in locals()

However, whenever I need to test this (the need is rather unusual), instead
of `if', I prefer writing:

try:
var1
except NameError:
pass # `var1' does not exist
else:
pass # `var1' exists
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top