Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Python Variable Checks: Safe Ways to Test a Name

· 5 min read · Home Tech

In this article
  1. Why Checking Variable Existence Matters
  2. The Core Methods: locals(), globals(), and vars()
  3. When to Use try/except NameError (and When Not To)
  4. Checking Attributes on Objects: hasattr() and getattr()
  5. Common Pitfalls and Misconceptions
  6. Performance and Style Considerations
  7. Alternatives: Using a Default or Sentinel
  8. Frequently Asked Questions

To safely test whether a variable name exists in Python, you should use locals(), globals(), or hasattr() depending on the context, rather than relying on a bare try/except NameError which can mask other errors. The most direct method is to check membership in the appropriate namespace dictionary, such as 'myvar' in locals() or 'myvar' in globals().

Why Checking Variable Existence Matters

In Python, variables are references to objects, and they live in namespaces. Sometimes you need to know whether a name has been assigned before using it, especially in long scripts, interactive sessions, or when dealing with optional configuration. A common mistake is to use a variable before it exists, leading to a NameError that crashes the program. Checking existence helps you write defensive code, but doing it incorrectly can introduce bugs or hide real issues.

The Core Methods: locals(), globals(), and vars()

Python stores variables in dictionaries. The built-in functions locals() and globals() return these dictionaries, and you can test membership with the in operator. For example:

  • 'x' in locals() – checks if x is defined in the current local scope.
  • 'x' in globals() – checks if x is defined in the global scope.
  • 'x' in vars(obj) – checks if an object has an attribute named x (though hasattr is usually clearer).

These methods are safe because they only inspect the namespace dictionary; they don’t execute any code or risk side effects. They are also precise: you know exactly which scope you are checking.

When to Use try/except NameError (and When Not To)

Some programmers use a try/except NameError block to test for a variable. While this works, it is generally discouraged because it catches any NameError in the block, including typos or missing imports inside the try clause. For example:

try:
    print(my_var)
except NameError:
    print("my_var not defined")

If my_var is not defined, it prints the message. But if the print function itself were misspelled (e.g., printt), you would also get a NameError and incorrectly assume my_var is missing. For simple checks, the dictionary membership approach is clearer and less error-prone.

Checking Attributes on Objects: hasattr() and getattr()

When you need to check if an object has a certain attribute (like a method or a property), use hasattr(). It is the standard, readable way:

  • hasattr(obj, 'attr_name') – returns True if the object has that attribute.
  • getattr(obj, 'attr_name', default) – returns the attribute value or a default if it doesn’t exist.

These are safe and widely used. For example, to check if a file object has a closed attribute, you can do if hasattr(f, 'closed'):. This is much better than catching AttributeError manually.

Common Pitfalls and Misconceptions

One misconception is that locals() returns a snapshot, so changes to the returned dictionary do not affect the actual local variables. That is true, but for checking existence it works fine. Another pitfall is using 'x' in dir() – dir() returns a list of names, but it includes built-ins and may be slower and less precise. Also, beware of checking for a variable that may be defined but set to None; the existence check will return True, but the value is still None. You may need to check both existence and value.

Performance and Style Considerations

In most scripts, the performance difference between these methods is negligible. However, if you are doing thousands of checks in a loop, dictionary membership (in) is fast and recommended. For readability, prefer hasattr() for attributes and in locals() for local variables. Avoid using try/except for simple existence checks unless you also need to handle other exceptions.

Alternatives: Using a Default or Sentinel

Sometimes you don’t need to check existence at all. You can use getattr() with a default, or use a dictionary to store your variables, or use the setdefault method. For example, instead of checking if a config variable exists, you can do:

config = {}
config.setdefault('debug', False)

This is often cleaner than checking existence. Similarly, you can use a sentinel object to distinguish between “not set” and “set to None”.

Frequently Asked Questions

What is the difference between locals() and globals()?

locals() returns a dictionary of the current local namespace, which inside a function includes local variables and parameters. globals() returns the global namespace, which contains module-level variables and imported names. At the module level, they are the same dictionary.

Can I check if a variable exists in an outer scope?

Yes, you can check 'x' in globals() for global variables, and for enclosing function scopes you would need to use nonlocal or inspect the function’s __closure__, which is rarely needed. In practice, you should design your code to avoid such checks.

Is using try/except NameError ever recommended?

It can be acceptable in very small, isolated cases where you are certain no other NameError can occur. However, it is generally better to use dictionary membership checks because they are explicit and less likely to hide bugs.

How do I check if a variable exists and is not None?

You can combine checks: 'x' in locals() and locals()['x'] is not None. Or use locals().get('x') is not None, but be aware that if the variable is not defined, .get() returns None, so you cannot distinguish between “not defined” and “defined as None” with that alone.

Does checking existence work for built-in names like len?

Built-in names are in the builtins module, not in locals() or globals(). To check if a name is available as a built-in, you can use 'len' in dir(__builtins__), but that is rarely necessary.