- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
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.
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.
Hello Rahul Traceback (most recent call last): File "main.py", line 5, in
print(name) NameError: name 'name' is not defined
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.
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.
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')
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.
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")
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 −
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)
Fruit's name: Apple Fruit's color: Red
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')
On executing the program above, the output is displayed as follows −
m is local variable g is an attribute x is a global variable
- Related Articles
- How do I check whether a file exists using Python?
- How do I check to see if a column name exists in a CachedRowSet in JDBC?
- How to check if a key exists in a Python dictionary?
- How to check if a python module exists without importing it?
- How to check if a file exists or not using Python?
- Python - Check if a variable is string
- How do I declare a global variable in Python class?
- How do I check if a string has alphabets or numbers in Python?
- How to check if a given key already exists in a Python dictionary?
- How do I call a Variable from Another Function in Python?
- How to check if a MySQL database exists?
- How do I assign a dictionary value to a variable in Python?