In Python, a NameError
exception is raised when a name is not found in the local or global namespace.
For example a NameError
is raised when a variable or function is referenced before it has been defined, or when the value of a variable is accessed outside of its scope.
The general causes of NameError are:
-
Using undefined variables
-
Misspelled identifiers
-
Using variables before they are defined
-
Incorrect usage of scope
Avoiding and Handling NameError Exceptions
The most obvious way to fix the NameError
exception is to ensure that your code is using the correct names for variables and objects. Make sure to double-check all variable names and object names.
Python keeps a dictionary of all the variables defined in the global and another for variables defined in the local namespaces. You can access these dictionaries using the built-in functions globals() and locals() respectively. This allows us to check whether a variable is already assigned using the "in"
operator before using it . For example:
Just like other exceptions, you can also use try-except
blocks for catching and handling the NameError
.