1Testing if a Variable Is Defined
2Credit: Hamish Lawson
3
4Problem
5You want to take different courses of action based on whether a variable is defined.
6
7Solution
8In 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:
9
10try: x
11except NameError: x = None
12Then it’s easy to test whether a variable is bound to None:
13
14if x is None:
15 some_fallback_operation( )
16else:
17 some_operation(x)