Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To check whether a bare name is defined in Python, first decide whether you need to inspect a namespace or whether your code should initialize the value. For a module-level name, test membership in globals(); for an explicitly managed value, initialize it or use a default. A variable holding None is still defined, so name existence and value checks are different questions.

Choose the check that matches what you mean

  • Is this name in the current module namespace? Use "name" in globals().
  • Is this name among the current local bindings? Use "name" in locals(), with the scope caveats below.
  • Does this object have an attribute? Use hasattr(obj, "attribute").
  • Does my program have a value to use? Initialize it, or use a default or sentinel.

Python resolves names according to the environment of the current code block. If it cannot find a name, it raises NameError, as described in the Python Language Reference, “Execution model”.

Check a module-level name with globals()

globals() returns the current module’s global namespace. Membership tests whether a key is present there; it does not test every name Python might resolve, nor does it inspect a function’s local or enclosing bindings.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if "config_value" in globals():
    use(config_value)
else:
    use_default()

This pattern is useful when the intended question is specifically whether the module namespace contains that key. It is not a general-purpose way to ask whether a name exists anywhere in the current scope.

Use locals() only for the current local namespace

locals() exposes bindings in the current local namespace, but its behavior depends on the scope. In optimized function scopes, it returns a fresh dictionary of current bindings. A membership check can inspect what is currently present:

def process():
    value = 12
    if "value" in locals():
        use(value)

Do not treat this as a universal inspection method for enclosing scopes, or as a way to create or assign a local variable by changing the returned mapping. For name-resolution rules and namespace details, see the Python built-ins documentation for locals().

Prefer initialization when your code controls the value

If your code determines whether a value will be supplied, make that state explicit rather than probing for an undeclared name:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
config_value = None

if config_value is not None:
    use(config_value)
else:
    use_default()

This tests whether the value is None, not whether the name exists. If None is a valid value that must be distinguished from “not provided,” use a unique sentinel:

MISSING = object()
config_value = MISSING

if config_value is MISSING:
    use_default()
else:
    use(config_value)

The sentinel makes absence distinct from any ordinary value, including None. This is a design pattern for values your code manages, not a universal replacement for checking a namespace.

Understand why a function can raise UnboundLocalError

A function-local assignment affects how Python classifies that name throughout the function body. If a function assigns to a name anywhere in its body, Python treats it as local unless the function declares it global or nonlocal. Reading it before its local binding can raise UnboundLocalError, a subclass of NameError.

value = "module value"

def process():
    print(value)  # Raises UnboundLocalError
    value = "local value"

The assignment makes value local throughout process(); the earlier read does not fall back to the module value. Check the scope and move or redesign the assignment rather than trying to solve this with a global namespace membership test. The Python FAQ’s local and global variable rules explains this classification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use hasattr() for attributes, not bare names

hasattr(obj, "attr") asks whether an object has an attribute named attr. It does not check whether a bare variable name is defined:

if hasattr(settings, "theme"):
    use(settings.theme)

This is appropriate when settings.theme is the value you intend to inspect. Likewise, a module can be treated as an object when you specifically want to test for one of its attributes. The documented contract is about an object and an attribute-name string; see Python’s hasattr() documentation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Avoid eval() for checking names

eval("name") is not a safer or clearer existence check. It evaluates code, and its access to nested scopes is limited to nonlocals already referenced in the calling scope. If you need to inspect a namespace, use membership in the relevant mapping instead. See the Python documentation for eval() for its behavior and warning.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.