Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Test to see if variable exists

Reply
Thread Tools

Test to see if variable exists

 
 
lamar_air
Guest
Posts: n/a
 
      08-12-2003
I need an if statement to test if a variable exists in a pyton script

eg. if var1 exists:
do this
else:
do this
 
Reply With Quote
 
 
 
 
John Hunter
Guest
Posts: n/a
 
      08-12-2003
>>>>> "lamar" == lamar air <(E-Mail Removed)> writes:

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



 
Reply With Quote
 
 
 
 
Gabriel Cooper
Guest
Posts: n/a
 
      08-12-2003
lamar_air wrote:

>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 ;] )


 
Reply With Quote
 
=?iso-8859-1?q?Fran=E7ois_Pinard?=
Guest
Posts: n/a
 
      08-12-2003
[Graham Breed]

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


> 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

--
François Pinard http://www.iro.umontreal.ca/~pinard

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
test to see if a variable exists Colin Summers Ruby 4 06-16-2007 03:44 PM
finding if file exists or not in apache webdav server and if exists what is the mime type of it.... Totan Java 0 04-17-2006 05:13 AM
test to see if object exists with new/delete usage Squid Seven C++ 11 07-11-2005 12:41 PM
Testing to see if a variable exists... Ivan Marsh Javascript 12 11-29-2003 10:39 PM
test test test test test test test Computer Support 2 07-02-2003 06:02 PM



Advertisments