In order to verify whether a python variable is defined or not. Use the following code which uses try, except
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.