Testing if a Variable Is Defined
Credit: Hamish Lawson
Problem
You want to take different courses of action based on whether a variable is defined.
Solution
In Python, all variables are expected
to be defined before use. The None object is a
value you often assign to signify that you have no real value for a
variable, as in:
try: x except NameError: x = None
Then it’s easy to test whether a variable is bound
to None:
if x is None:
some_fallback_operation( )
else:
some_operation(x)Discussion
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 assigned the
None object. Attempting to access a variable that
hasn’t previously been defined raises a
NameError exception (which you can handle with
a try/except statement, as you
can for any other Python exception).
It is 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 clause and assigning it the
None object if the access raises a
NameError exception. Note that
None is really nothing magical, just a built-in object used by convention (and returned by functions that exit without returning anything specific). You can use any other value suitable for your purposes to initialize undefined variables; for a powerful and interesting example, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access