How to check if a variable exists in Python

Created
Modified

Using locals Function

The locals() function returns the dictionary of the current local symbol table.

#!/usr/bin/python3

vName = 1

if 'vName' in locals():
  print("exists")
exists

Using globals Function

The globals() function returns the dictionary of the current global symbol table.

#!/usr/bin/python3

vName = 1

if 'vName' in global():
  print("exists")
exists

Using hasattr Method

To check if an object has an attribute:

#!/usr/bin/python3

class Person:
  name = 'Ada'

person = Person()
if hasattr(person, 'name'):
  print("exists")
exists

Related Tags