HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythonCriticalCanonical

How do I check if a variable exists?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
checkexistshowvariable

Problem

I want to check if a variable exists. Now I'm doing something like this:

try:
    myVar
except NameError:
    # Do something.


Are there other ways without exceptions?

Solution

To check the existence of a local variable:

if 'myVar' in locals():
  # myVar exists.


To check the existence of a global variable:

if 'myVar' in globals():
  # myVar exists.


To check if an object has an attribute:

if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

Code Snippets

if 'myVar' in locals():
  # myVar exists.
if 'myVar' in globals():
  # myVar exists.
if hasattr(obj, 'attr_name'):
  # obj.attr_name exists.

Context

Stack Overflow Q#843277, score: 2373

Revisions (0)

No revisions yet.