locals() function in Python
Last Updated :
15 May, 2025
locals() function in Python returns a dictionary representing the current local symbol table, allowing you to inspect all local variables within the current scope e.g., inside a function or block. Example:
Python
def fun(a, b):
res = a + b
print(locals())
fun(3, 7)
Output{'a': 3, 'b': 7, 'res': 10}
Explanation: fun() defines three local variables a, b and res. The locals() function returns a dictionary of these variables and their values.
Symbol table in Python
A symbol table is a data structure maintained by the Python interpreter that stores information about the program’s variables, functions, classes, etc.Python maintains different types of symbol tables:
Type | Description |
---|
Local Symbol Table | Stores information about variables defined within a function/block |
Global Symbol Table | Contains info about global variables and functions defined at top level |
Built-in Symbol Table | Contains built-in functions and exceptions like len(), Exception, etc. |
Syntax of locals()
locals()
Parameters: This function does not take any input parameter.
Return Type: This returns the information stored in local symbol table.
Behavior of locals() in different scopes
Example 1: Using locals() with no local variables
Python
def fun():
print(locals())
fun()
Explanation: Since there are no local variables inside fun(), locals() returns an empty dictionary.
Example 2: Using locals() with local variables
Python
def fun():
user = "Alice"
age = 25
print(locals())
fun()
Output{'user': 'Alice', 'age': 25}
Explanation: fun() define two local variables user and age. When we call locals(), it returns a dictionary showing all the local variables and their values within that function's scope.
Can locals() modify local variables?
Unlike globals(), which can modify global variables, locals() does not allow modifying local variables inside a function.
Example: Attempting to modify local variables using locals()
Python
def fun():
name = "Ankit"
# attempting to modify name
locals()['name'] = "Sri Ram"
print(name)
fun()
Explanation: Even though locals()['name'] is modified, the change does not reflect in the actual variable because locals() returns a copy of the local symbol table, not a live reference.
Using locals() in global Scope
In the global scope, locals() behaves just like globals() since the local and global symbol tables are the same. Example:
Python
x = 10
print(locals())
print(globals())
Output{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f5ee5639e00>, '__spec__': None, '__annotations__': {}, '__builtin...
Explanation: In global context, locals() and globals() refer to the same dictionary.
Practical examples
Example 1: Here, we use locals() to access a local variable using a dictionary-style lookup.
Python
def fun():
user = "Vishakshi"
print("Hello", locals()['user'])
fun()
Explanation: fun() creates a local variable user. Instead of accessing it directly, locals()['user'] retrieves its value dynamically.
Example 2: This example shows how locals() can be used with string formatting to inject local variable values into a template string.
Python
def fun(name, age):
t = "My name is {name} and I am {age} years old."
print(t.format(**locals()))
fun("Vishakshi", 22)
OutputMy name is Vishakshi and I am 22 years old.
Explanation: locals() provides the local variables name and age as keyword arguments to format(). This makes the code more flexible and avoids writing .format(name=name, age=age) manually.
global() vs locals()-Comparison Table
Knowing the difference between the two helps you debug better, write smarter code and even modify behavior dynamically when needed. Let’s understand them through the following table:
Feature | globals() | locals() |
---|
Returns | Global symbol table | Local symbol table |
---|
Scope Level | Global/module-level variables and functions | Variables inside the current function/block |
---|
Modifiable? | Yes, modifies global variables | No, does not modify local variables |
---|
Access global variables? | Yes | No (inside a function) |
---|
Behavior in global scope | Same as locals() | Same as globals() |
---|
Used for? | Modifying and accessing global variables | Inspecting local variables |
---|
Related articles
Similar Reads
locals() function-Python
locals() function in Python returns a dictionary representing the current local symbol table, allowing you to inspect all local variables within the current scope e.g., inside a function or block. Example:Pythondef fun(a, b): res = a + b print(locals()) fun(3, 7)Output{'a': 3, 'b': 7, 'res': 10} Exp
4 min read
Python - globals() function
In Python, the globals() function is used to return the global symbol table - a dictionary representing all the global variables in the current module or script. It provides access to the global variables that are defined in the current scope. This function is particularly useful when you want to in
2 min read
ord() function in Python
Python ord() function returns the Unicode code of a given single character. It is a modern encoding standard that aims to represent every character in every language.Unicode includes:ASCII characters (first 128 code points)Emojis, currency symbols, accented characters, etc.For example, unicode of 'A
2 min read
now() function in Python
Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Syntax : datetime.now(tz) Parameters : tz : Specified time zone of which current time and date is required. (Uses
3 min read
Python int() Function
The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part.Example:In this example, we passed a string as an argument to the int() function and printed it.Pythonage = "21" print("age =", int(age)
3 min read
Partial Functions in Python
Partial functions allow us to fix a certain number of arguments of a function and generate a new function. In this article, we will try to understand the concept of Partial Functions with different examples in Python.What are Partial functions and the use of partial functions in Python?Partial funct
5 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
Python print() function
The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
id() function in Python
In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
3 min read
Python input() Function
Python input() function is used to take user input. By default, it returns the user input in form of a string.input() Function Syntax: input(prompt)prompt [optional]: any string value to display as input messageEx: input("What is your name? ")Returns: Return a string value as input by the user.By de
4 min read