undefined variable ?

M

Michael Hoffman

vertigo said:
How can i check if variable named var1 exists ?

It's frequently a better approach to assume that it does and catch an
exception if it doesn't.

try:
var1
except NameError:
var1 = "neW"

But why do you want to do this?
 
G

Guido Gloor

Are exceptions cheap in Python then? Coming from Java, I know there's
all sorts of overhead involved in creating and throwing an exception
there...
 
J

Jeff Epler

Hello
How can i check if variable named var1 exists ?

While it's possible to do that, you'll do better in the long run by
learning to write programs in the Python style, which does not often
perform checks like "does the named variable exist". For instance,
instead of writing
def my_max(seq):
for i in seq:
if undefined("largest") or i > largest: largest = i
return largest
you would write
def my_max(seq):
largest = None
for i in seq:
if largest is None or i > largest: largest = i
or
def my_max(seq):
largest = seq[0]
for i in seq:
if i > largest: largest = i

It's a little more common to check whether an object has a given
attribute:
def write_or_send(f, s):
# "look-before-you-leap" style
if hasattr(f, "write"): return f.write(s)
return f.send(s)

And checking whether a key is in a dictionary is frequent:
if "spam" not in pantry: pantry["spam"] = buy("spam")

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.6 (GNU/Linux)

iD8DBQFBcUOlJd01MZaTXX0RAnwqAJ9BEiZyFXPdVD4F/Wnc3S2NsuYvGgCfbmq+
+mUQ3j5gjkCowI1SShWXPto=
=5iRN
-----END PGP SIGNATURE-----
 
J

Josiah Carlson

Are exceptions cheap in Python then? Coming from Java, I know there's
all sorts of overhead involved in creating and throwing an exception
there...

They are not free, but they aren't that bad either...
... for i in xrange(n):
... try:
... j = 1
... except:
... pass
...... for i in xrange(n):
... try:
... raise #generally improper use
... except:
... pass
...... for i in xrange(n):
... try:
... j = l
... except:
... pass
...... for i in xrange(n):
... j = 1
...

The no-exception version runs in ~.58 seconds, with-exception handling
(none raised) runs in ~.92 seconds, the first exception raiser runs in
~7.7 seconds, and the name error on assignment runs in ~27 seconds.


As long as you aren't relying on exception handling as a major part of
your algorithms, and are actually using them as /error handling/, I
wouldn't worry too much; the rest of us don't (we prefer properly
running scripts).

- Josiah
 

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,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top