Introduction: Python locals() Function
When working with Python, there are situations where you need to inspect or access the variables available inside the current scope. Whether you’re debugging a function, examining local data, or understanding how variables are stored, manually tracking every variable can become difficult as programs grow.
Without a built-in solution, checking the values of local variables often requires multiple print() statements or additional debugging code, making programs harder to read and maintain.
A simple and convenient solution to these situations is the Python locals() Function.
What it is: The locals() function is a built-in Python function that returns a dictionary containing the local symbol table of the current scope. Each dictionary key represents a local variable name, while its corresponding value stores the current value of that variable.
Take a look at a quick example to see how it works.
You can also explore its real-world use cases to learn where it is commonly used.
Now let’s understand the syntax, parameters, return value, and practical examples of the locals() function.
💡 Tip: The locals() function is just one of Python’s many built-in functions. Explore the
Python Built-in Functions Learning Guide to discover more functions with beginner-friendly explanations and practical examples.
Syntax, Parameters, Return Value and Examples: Python locals() Function
The following section explains the syntax, parameters, return value, and a quick example of the Python locals() Function.
Syntax
locals()
Parameters
| Parameter | Description |
|---|---|
| None | The locals() function does not accept any arguments. |
Return Value
| Return Value | Description |
|---|---|
dict |
Returns a dictionary containing the local variables available in the current scope. |
Quick Example
The following example displays the local variables inside a function.
def student():
name = "John"
age = 18
print(locals())
student()
# Output:
{'name': 'John', 'age': 18}
The locals() function returns a dictionary containing all the local variables defined inside the student() function, along with their current values.
How the Python locals() Function Works
- The
locals()function does not require any arguments. - It collects all variables available in the current local scope.
- The variables are returned as a dictionary.
- Each dictionary key represents a variable name, while the corresponding value stores its current value.
- It is commonly used for debugging, inspection, and understanding variable scope.
Examples: Python locals() Function
The following examples show how the Python locals() Function works in different programming scenarios.
Example 1: Viewing Local Variables Inside a Function
def student():
name = "Alice"
age = 20
print(locals())
student()
# Output:
{'name': 'Alice', 'age': 20}
Explanation: The locals() function returns a dictionary containing every variable created inside the student() function along with its current value.
Example 2: Accessing a Specific Local Variable
def employee():
name = "David"
salary = 55000
local_data = locals()
print(local_data["salary"])
employee()
# Output:
55000
Explanation: Since locals() returns a dictionary, individual variables can be accessed using their names as dictionary keys.
Example 3: Displaying Local Variables After Calculations
def calculate():
a = 15
b = 10
total = a + b
print(locals())
calculate()
# Output:
{'a': 15, 'b': 10, 'total': 25}
Explanation: Variables created during execution also appear in the local symbol table. Here, the calculated value of total is included along with a and b.
Example 4: Using locals() with User Input
def greet():
name = input("Enter your name: ")
print(locals())
greet()
# Sample Output:
Enter your name: Emma
{'name': 'Emma'}
Explanation: After the user enters a value, it becomes part of the function’s local scope. Calling locals() immediately shows the updated local variable.
Example 5: Counting Local Variables
def details():
city = "Delhi"
country = "India"
pin = 110001
print(len(locals()))
details()
# Output:
3
Explanation: Rather than printing the entire dictionary, this example counts how many local variables exist in the current scope using len(locals()).
Example 6: Iterating Through Local Variables
def product():
name = "Laptop"
price = 65000
brand = "ABC"
for key, value in locals().items():
print(key, "=", value)
product()
# Output:
name = Laptop
price = 65000
brand = ABC
Explanation: The dictionary returned by locals() can be traversed just like any other dictionary, making it easy to inspect every local variable and its value.
Example 7: Calling locals() Outside a Function
x = 100
message = "Hello"
print(locals())
# Output:
{'x': 100, 'message': 'Hello', ...}
Explanation: Outside a function, the local scope is the global scope. Therefore, locals() returns the same variables that are available globally, along with other names maintained by the Python interpreter.
Use Cases: When to use the locals() Function
Below are some common situations where the Python locals() Function becomes useful:
- Inspecting local variables during debugging.
- Viewing the current state of a function.
- Examining variables created during program execution.
- Displaying variable names and values dynamically.
- Understanding Python’s local variable scope.
- Building debugging and diagnostic utilities.
Key Takeaways: locals() Function
Before wrapping up, here are the key points to remember about the Python locals() Function:
- The
locals()function returns a dictionary containing the current local symbol table. - It does not accept any arguments.
- Each dictionary key represents a local variable name.
- Each dictionary value stores the current value of that variable.
- Inside a function, it returns only local variables defined in that function.
- Outside a function, it behaves similarly to
globals()because the local scope is the global scope. - It is mainly used for debugging, inspection, and understanding variable scope.
In short, the Python locals() Function provides an easy way to inspect the variables available in the current scope, making debugging, learning, and program analysis much more convenient.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.