How do I check if a Python variable exists?


Variables are defined as the containers used to store some data. They represent a memory location. Any type of data or value can be stored in a variable in Python, including integers, strings, float, Boolean etc.

In Python, a variable's data type does not need to be specified when it is defined in a program. However, before any function or application can use variables, they must be defined first. It can be done by simply assigning a value to a name as shown below −

x = 5

Here, ‘x’ is the name of a variable. Also, since x holds an integer value, it is an integer variable.

Scope of a Variable

Variables may not be accessible at all times in a program. The declaration of the variable determines this. Variable scope determines where an identifier can be accessed within a program. Two basic scopes exist in Python variables.

  • Local variables

  • Global variables

Local Variables

Variables defined in a block are generally only available within that block. Outside of the block, they cannot be accessed. These type of variables are known as local variables. Local variables behave similarly to formal argument identifiers. The following example illustrates this point. If they are accessed from outside their scope, the NameError exception is triggered.

Example

def greet():
   name = 'Rahul'
   print('Hello ', name)
greet()
print(name)

In the example above, ‘name’ is a local variable for the greet() function, and cannot be accessed outside of it.

Output

Hello  Rahul
Traceback (most recent call last):
  File "main.py", line 5, in 
print(name)
NameError: name 'name' is not defined

Global Variables

Global variables are variables that exist outside of function blocks. Any function can access its value. It is necessary to initialize the name variable before defining the function.

name = 'Rahul'
def greet():
   print("Hello",name)
greet()

If we execute the simple program above, the result is produced as given below.

Output

Hello Rahul

Verifying the Existence of a Variable

A variable can be checked whether it exists with exceptions, but this isn't recommended since we don't always know whether a variable is defined. The safest and the most optimal way to check whether a variable exists in Python is by using the following methods.

  • Find out if a variable exists in a certain block using the locals() method.

  • A variable's existence throughout the program can be determined using the globals() method.

Using the Locals() Method

The existence of a local variable will be verified using the locals() function. In the local namespace, locals() returns a dictionary that contains current active variable names as its keys.

Example

In the example below, a function “local_func” is defined and a local variable “var” of string type is created. Since the locals() method returns the dictionary containing the current local variables in the form of keys, we can use the “in” operator to check if the variable exists. To be more accurate, we can also call the locals() method outside the local namespace to check its existence.

def local_func():
    var = "Test"
    if 'var' in locals():
        print ('variable found in local namespace')
    else:
        print ('variable not found in the local namespace')
local_func()
if 'var' in locals():
    print ('variable found in the global namespace')
else:
    print ('variable not found in the global namespace')

Output

variable found in local namespace
variable not found in the global namespace

Using the Globals() Method

A variable's status in the global namespace is determined using the globals() method. Global variable names are represented as strings in a dictionary returned by this method.

Example

A variable name string can be checked in the dictionary using the “in” operator. An existing variable is one that is present in the global namespace, if true; otherwise, it is not present.

var = "Python" 
if 'var' in globals(): 
    print ("variable present in global namespace") 
else: 
    print ("variable does not present in global namespace")

Output

variable present in global namespace

Check if the Variable exists in Class

The hasattr() function can be used to see if a variable exists in a class. The return value of this method will be true if an object contains the given named attribute and false if it does not.

The syntax of hasattr() method is −

hasattr(object, name)

Example

In the example below, we are defining a class “fruit” containing attributes describing its features. Using the hasattr() method, we are checking whether certain attributes are present in it or not; if yes, their values are displayed.

class fruit:
    color = 'Red'
    name = 'Apple'
frt = fruit()
if hasattr(frt, 'name'):
    print("Fruit's name:", frt.name)
if hasattr(frt, 'color'):
    print("Fruit's color:", frt.color)

Output

Fruit's name: Apple
Fruit's color: Red

Example

Let us see another example to check whether a variable exists in a Python program or not.

x =10
class foo:
   g = 'rt'
   def bar(self):
      m=6
      if 'm' in locals():
         print ('m is local variable')
      else:
         print ('m is not a local variable')
f = foo()
f.bar()
if hasattr(f, 'g'):
   print ('g is an attribute')
else:
   print ("g is not an attribute")
if 'x' in globals():
   print ('x is a global variable')

Output

On executing the program above, the output is displayed as follows −

m is local variable
g is an attribute
x is a global variable

Updated on: 22-Feb-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements