Viewing all defined variables in Python
Last Updated :
11 Dec, 2020
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code.
Method 1: Using dir() function
dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all declared and built-in variables. There are two different ways to view all defined variables using dir( ). They are discussed below.
When no user-defined variable starts with '__' :
- Define some variables of various types that are not starting with '__'
- Call dir and store it in a variable. It stores all the variable names defined before in the form of a list and stores the variable names as a string.
- Iterate over the whole list where dir( ) is stored.
- Print the item if it doesn't start with '__'
Example:
Python3
# Define some variables of various types
# that are not starting with '__'
var2 = "Welcome to geeksforgeeks"
var3 = {"1": "a", "2": "b"}
var4 = 25
var5 = [1, 2, 3, 4, 5]
var6 = (58, 59)
# call dir and store it in a variable.
# It stores all the variable names defined
# before in the form of a list
# and stores the variable names as a string.
all_variables = dir()
# Iterate over the whole list where dir( )
# is stored.
for name in all_variables:
# Print the item if it doesn't start with '__'
if not name.startswith('__'):
myvalue = eval(name)
print(name, "is", type(myvalue), "and is equal to ", myvalue)
Output:
var2 is <class 'str'> and is equal to Welcome to geeksforgeeks
var3 is <class 'dict'> and is equal to {'1': 'a', '2': 'b'}
var4 is <class 'int'> and is equal to 25
var5 is <class 'list'> and is equal to [1, 2, 3, 4, 5]
var6 is <class 'tuple'> and is equal to (58, 59)
Storing the built-in variables and ignoring them
- Create a new variable and store all built-in functions within it using dir( ).
- Define some variables of various types.
- Again call dir and store it in a list subtracting the built-in variables stored previously.
- Iterate over the whole list.
- Print the desired items
Example:
Python3
# Create a new variable and store all
# built-in functions within it using dir( ).
not_my_data = set(dir())
# Define some variables of various types.
var2 = "Welcome to geeksforgeeks"
var3 = {"1": "a", "2": "b"}
var4 = 25
var5 = [1, 2, 3, 4, 5]
var6 = (58, 59)
# Again call dir and store it in a list
# subtracting the built-in variables stored
# previously.
my_data = set(dir()) - not_my_data
# Iterate over the whole list is stored.
for name in my_data:
# Exclude the un-necessary variable named not_my_data
if name != "not_my_data":
val = eval(name)
print(name, "is", type(val), "and is equal to ", val)
Output:
var2 is <class 'str'> and is equal to Welcome to geeksforgeeks
var3 is <class 'dict'> and is equal to {'1': 'a', '2': 'b'}
var6 is <class 'tuple'> and is equal to (58, 59)
var4 is <class 'int'> and is equal to 25
var5 is <class 'list'> and is equal to [1, 2, 3, 4, 5]
Method 2: To print local and global variables
Locals() is a built-in function that returns a list of all local variables in that particular scope. And globals() does the same with the global variables.
Approach
- Create a list of all global variables using globals( ) function, to store the built-in global variables.
- Declare some global variables
- Declare a function.
- Declare some local variables inside it.
- Store all the local variables in a list, using locals keyword.
- Iterate over the list and print the local variables.
- Store the global variables in a list using globals keyword and subtract the previously created list of built-in global variables from it.
- Print them.
- Call the function.
Example:
Python3
# Create a list of all global variables using
# globals( ) function, To store the built-in
# global variables.
not_my_data = set(globals())
# Declare some global variables
foo5 = "hii"
foo6 = 7
# Declare a function.
def func():
# Declare some local variables inside it.
var2 = "Welcome to geeksforgeeks"
var3 = {"1": "a", "2": "b"}
var4 = 25
var5 = [1, 2, 3, 4, 5]
var6 = (58, 59)
# Store all the local variables in a list,
# using locals keyword.
locals_stored = set(locals())
# Iterate over the list and print the local
# variables.
print("Printing Local Variables")
for name in locals_stored:
val = eval(name)
print(name, "is", type(val), "and is equal to ", val)
# Store the global variables in a list using
# globals keyword and subtract the previously
# created list of built-in global variables from it.
globals_stored = set(globals())-not_my_data
# Print the global variables
print("\nPrinting Global Variables")
for name in globals_stored:
# Excluding func and not_my_data as they are
# also considered as a global variable
if name != "not_my_data" and name != "func":
val = eval(name)
print(name, "is", type(val), "and is equal to ", val)
# Call the function.
func()
Output:
Printing Local Variables
var2 is <class 'str'> and is equal to Welcome to geeksforgeeks
var6 is <class 'tuple'> and is equal to (58, 59)
var4 is <class 'int'> and is equal to 25
var5 is <class 'list'> and is equal to [1, 2, 3, 4, 5]
var3 is <class 'dict'> and is equal to {'1': 'a', '2': 'b'}
Printing Global Variables
foo6 is <class 'int'> and is equal to 7
foo5 is <class 'str'> and is equal to hii
Similar Reads
Environment Variables in Python
Environment variables are key-value pairs that live in our system's environment. Python reads some of these variables at startup to determine how to behave, for example, where to look for modules or whether to enter interactive mode.If thereâs ever a conflict between an environment variable and a co
3 min read
Context Variables in Python
Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work wi
4 min read
Global and Local Variables in Python
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only insid
7 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of âPrivateâ instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a n
3 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-va
3 min read
Assign Function to a Variable in Python
In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print(
3 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
3 min read
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
2 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a cl
2 min read