October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Check Whether a Python Variable Exists: The Right Test for Each Scope

Python variable checks depend on scope and on whether you mean a bound name, a non-None value, or an object attribute. Use explicit initialization when you control the value; inspect globals() or locals() only when namespace membership is the question.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

For code you control, initialize the value or give it an explicit default; that is usually clearer than probing whether a name exists. If you deliberately need to inspect a namespace, test for the name as a string in the right mapping: "config_value" in globals() for the current module, or "config_value" in locals() for the current local namespace. The choice matters because Python resolves names according to scope, and an unresolved name raises NameError.

Choose the check that matches what you mean

“Does this variable exist?” can mean several different things: whether a name is bound in the module namespace, whether a local name is present, whether a value is not None, or whether an object has an attribute. Those are different questions, so there is no single universal existence check.

As an Amazon Associate I earn from qualifying purchases.

What you need to know Use
Whether a name is in the current module namespace "name" in globals()
Whether a name is in the current local namespace "name" in locals()
Whether a value is not None value is not None, after the name has been safely bound
Whether an object has an attribute hasattr(obj, "attribute")

The Python Language Reference explains that if a name is not found, Python raises NameError. A function can also raise UnboundLocalError, a subclass of NameError, when a local name is read before it has been assigned.

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

When you control the value, initialize it instead

If your program determines whether a value will be available, set it deliberately before the conditional. This avoids making later code depend on probing Python’s namespaces.

config_value = None

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

This checks whether the value is None, not whether the variable name exists. If None is itself a valid value and must be distinguished from “not supplied,” use a unique sentinel:

MISSING = object()
config_value = MISSING

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

The sentinel represents a separate “no value supplied” state, leaving None available as a real value.

Check a module-level name with globals()

globals() returns the current module namespace. Membership tests whether the string key is present there:

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 is appropriate when the question is specifically whether config_value is bound in the current module. It does not tell you whether a name exists only as a local variable in a function or in an enclosing function scope. See the Python Language Reference on execution and name resolution.

Use locals() only for the current local namespace

locals() exposes bindings in the current local namespace. Inside a function, you can ask whether a name appears in that namespace:

def process():
    optional_value = 10
    if "optional_value" in locals():
        use(optional_value)

Interpret this in the scope where the call occurs. It is not a general-purpose search for names in arbitrary enclosing scopes, and it is not a reliable way to create or assign a local variable. Python’s built-in documentation also notes that in optimized function scopes, locals() returns a fresh dictionary of current bindings. For namespace inspection, consult the documentation for locals().

Why a function assignment can cause UnboundLocalError

Python classifies a name as local throughout a function if that function assigns to it anywhere, unless the name is declared global or nonlocal. That means a name that appears to refer to a module-level value may instead be treated as a local name—and reading it before the assignment fails.

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

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

Because process() assigns to value, Python treats it as local in the function body. The earlier read happens before that local binding. The fix is usually to restructure the function so it receives or initializes its value explicitly. If you truly intend to use the module binding, declare global value before using it; use nonlocal when referring to a binding in an enclosing function. The Python FAQ explains the local and global assignment rule.

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

Use hasattr() for attributes, not bare variable names

hasattr(obj, "attr") asks whether obj has an attribute named attr. It does not check whether a bare variable called attr exists.

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

For a module attribute, the module is still an object, so hasattr(module, "name") can answer that attribute question. It is not a substitute for checking an unrelated local or global name. The built-in’s contract is documented under hasattr().

Avoid eval() for existence checks

Do not use eval("name") as a shortcut for checking whether a variable exists. It attempts to evaluate an expression rather than test membership in a namespace, and Python’s documentation warns that eval() can execute arbitrary code. Its access to nested scopes is also limited to nonlocal names already referenced in the calling scope. If you intentionally need to inspect a namespace, explicit membership in globals() or locals() makes the target scope clear. See the eval() documentation.

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

Quick decision guide

  • If your code owns the value’s lifecycle, initialize it or use an explicit default.
  • If None is a meaningful value, use a unique sentinel to represent absence.
  • If you specifically need to inspect module-level bindings, test the key in globals().
  • If you need to inspect the current local namespace, test the key in locals() and keep its scope limitations in mind.
  • If you mean an object property, use hasattr() with the object and attribute name.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.