Check if variable is defined

Tim Peters tim.one at home.com
Thu May 17 10:28:09 CEST 2001


[Todd A. Jacobs]
> I'm having a lot of trouble doing something that was simple in Perl:
> specifically, I want to create if/else clauses that take action only
> if a particular variable is undefined. How do I check to see if a
> variable or object has already been defined?

Perl's notion of "defined" vs "undefined" values doesn't exist in Python.

> If there's no better way, I suppose I could try to catch the exception,
> but that seems like a bit of a kludge,

You're basing program logic on whether a variable has or hasn't yet been
assigned a value, and call *exceptions* a kludge?  Heh heh.

> especially if I have to create the exception in order to find out
> what exception the interpreter throws first.

If you reference a variable that hasn't yet been assigned a value (not the
same thing as asking whether a vrbl has an undefined value in Perl terms, but
kinda close if you squint), Python raises UnboundLocalError (if it's a local
vrbl) else NameError.  The former is a subclass of the latter, so

    try:
        beatsme
    except NameError:
        print "beatsme wasn't bound yet"
    else:
        print "was"

always works.  But it's the norm in Python for programmers to consider
NameError a bug in their code, so you'll rarely see that construct in
experienced programmers' code.  Initializing variables is better practice (in
Python or any other language).  If there isn't a compelling initial value,
then it's common to initialize to None, and later do

    if beatsme is None:
        print "beatsme wasn't assigned anything meaningful yet"
    else:
        print "was"





More information about the Python-list mailing list