Welcome, guest | Sign In | My Account | Store | Cart

You want to take different courses of action based on whether a variable is defined or not.

Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Ensure variable is defined
try:
    x
except NameError:
    x = None

# Test whether variable is defined to be None
if x is None:
    some_fallback_operation()
else:
    some_operation(x)

Python doesn't have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use - even if initially just assigned the None object. Attempting to access a variable that hasn't previously been defined will raise an exception.

It is generally considered unusual in Python not to know whether a variable has already been defined. But if you are nevertheless in this situation, you can make sure that a given variable is in fact defined (as None, if nothing else) by attempting to access it inside a 'try' block and assigning it the None object should it raise a NameError exception.

Many situations which might be thought would give rise to undefined variables, such as processing configuration files or web forms, can be better handled by employing a dictionary and testing for the presence of a key with the has_key() method.

5 comments

Jürgen Hermann 22 years, 9 months ago  # | flag

Use has_key on the internal dicts. If you know where the variable is located (local or global), you can use the much more efficient "vars().has_key('x')" or "globals().has_key('x')".

Hamish Lawson (author) 22 years, 9 months ago  # | flag

But will a variable always be in globals() or locals()? If you do know that the variable is in either locals() or globals(), then using has_key() on those dictionaries is certainly preferable. However, in one of Alex Martelli's posts it seemed to be his understanding that the introduction of nested scopes could mean that a variable may not be in either of those scopes. Attempting to access the variable and catching the possible exception is so far the only general technique I've come across for testing a variable's definedness.

Brendan Arnold 19 years, 1 month ago  # | flag

Testing for an undefined global variable. I had problems when implementing the above when the variable I was testing for was to be a global variable, i.e.

try:
    myVar
except NameError:
    global myVar
    myVar = 1

This gave a warning that myVar is used prior to global declaration. Anyone know how to deal with this?

Karl Bartel 19 years ago  # | flag

It looks like only the second myVar is global. Try declaring it as global above the try.

global myVar
try:
    myVar
except NameError:
    myVar = 1
karkfum 14 years, 5 months ago  # | flag

In current versions of python, you can use "in" to check existence in both List and Dicts of defined vars:

A good example of this is the __file__ var, which is not defined when the python interpreter is run interactively from a DOS shell, or if a py2exe executable is run.

__file__ is normally found in the variable List returned by "dir()", so you can avoid raising an exception by using:

if '__file__' in dir():   # check the List 
    print __file__ 

if '__doc__' in locals():  # check the Dict 
    print __doc__
Created by Hamish Lawson on Tue, 5 Jun 2001 (PSF)
Python recipes (4591)
Hamish Lawson's recipes (6)
Python Cookbook Edition 1 (103)

Required Modules

  • (none specified)

Other Information and Tasks