On Sat, Oct 16, 2004 at 11:43:08AM +0200, vertigo wrote:
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-----