Wrap access to the variable in a try ... except NameError: block (the most Pythonic EAFP approach), or check membership in the appropriate namespace dictionary ("var_name" in locals(), "var_name" in globals(), or hasattr(obj, "attr_name") for object/module attributes)—avoiding the need to check variable existence altogether whenever possible by initializing variables to None up front.
Basic Example
# 1. Recommended (EAFP - Pythonic): Try using the variable and catch NameError
try:
print(user_token)
except NameError:
user_token = "default_token"
# 2. Scope-dictionary lookup (LBYL): Check local or global symbol tables explicitly
x = 42
is_local = "x" in locals() # True (if defined in current local scope)
is_global = "x" in globals() # True (if defined at module level)
# 3. Better design pattern: Initialize to None beforehand instead of testing existence
result = None
if some_condition := True:
result = "computed_value"
if result is not None:
print(result)
Key Details & Edge Cases
- Scope difference between
locals(),globals(), and enclosing (nonlocal) closures:"var" in globals()checks only the current module’s top-level namespace—it returnsFalsefor variables defined inside a function."var" in locals()inside a function checks only that function’s local frame—it returnsFalsefor module-level globals and built-ins (len,print).- Closure / nested function gotcha: Inside a nested function, a variable from an outer enclosing function (
nonlocal) is not inlocals()unless it is actually referenced inside the inner function’s body.try ... except NameError:handles local, enclosing (nonlocal), global, and built-in scopes seamlessly in exact LEGB resolution order.
- Checking attributes on objects, classes, or modules (
hasattr()): Never uselocals()orglobals()to check if a module or instance defines a member—usehasattr(obj, "attr_name")(orgetattr(obj, "attr_name", default)):import math if hasattr(math, "tau"): print(math.tau) - Why
try ... except NameError:must stay tight around the variable name: Keep only the single variable lookup inside thetryblock (try: val = maybe_undefined) rather than wrapping a large block of code, so an accidentalNameErrortypo deeper inside your logic isn’t silently swallowed. - Initialize to
Noneinstead of checkingNameErrorin clean code: Needing"var" in locals()usually indicates a conditional branch (if/elseortry/except) failed to assign a variable on every path. Settingvar = Nonebefore theifstatement and checkingif var is not None:is faster, clearer, and supported by static type checkers (mypy/pyright).
Comparison of Variable & Attribute Existence Checks in Python
| Method | Syntax | Scopes Checked | Safe for Enclosing (nonlocal) Vars? |
Best Used When |
|---|---|---|---|---|
try ... except NameError: |
try: x except NameError: ... |
All LEGB scopes (Local, Enclosing, Global, Built-in) | Yes | Checking whether an identifier exists anywhere in the active resolution chain. |
"x" in locals() |
"x" in locals() |
Current local scope only | Only if referenced in body | Inspecting variables bound inside the current function or frame. |
"x" in globals() |
"x" in globals() |
Current module’s top-level scope only | No | Checking whether a module-level global variable or configuration constant exists. |
hasattr(obj, "x") |
hasattr(module_or_obj, "x") |
Object / class / module attributes | N/A | Checking if an instance, class, or imported module defines a specific attribute or method. |
Sentinel Initialization (None) |
x = None; ... if x is not None: |
Explicit local/global binding | Yes | Standard production code where a variable may or may not be populated by a branch. |
You must log in or register to comment.
