undefined variable ?

Jeff Epler jepler at unpythonic.net
Sat Oct 16 17:52:06 CEST 2004

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
    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
    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")

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20041016/60cb355b/attachment.sig>

More information about the Python-list mailing list