Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find number of local variables in a function
In this article, we will learn how to find the number of local variables in a function using Python's built-in code object attributes.
Problem statement ? We are given a function, and we need to display the number of local variables defined within that function.
Understanding Local Variables
Local variables are variables that are defined inside a function and can only be accessed within that function's scope. Python stores information about functions in code objects, which include the count of local variables.
Using __code__.co_nlocals
Every function in Python has a __code__ attribute that contains a code object. The co_nlocals attribute of this code object returns the number of local variables in the function.
Example 1: Basic Function with Local Variables
# Function with multiple local variables
def scope():
a = 25.5
b = 5
str_ = 'Tutorialspoint'
# Check number of local variables
print("Number of local variables available:", scope.__code__.co_nlocals)
Number of local variables available: 3
Example 2: Comparing Functions
Let's compare an empty function with a function containing local variables ?
# Empty function
def empty():
pass
# Function with local variables
def scope():
a, b, c = 9, 23.4, True
text = 'Tutorialspoint'
# Check local variables count
print("Empty function local variables:", empty.__code__.co_nlocals)
print("Scope function local variables:", scope.__code__.co_nlocals)
Empty function local variables: 0 Scope function local variables: 4
Example 3: Function with Parameters
Parameters are also counted as local variables ?
# Function with parameters and local variables
def calculate(x, y):
result = x + y
message = "Calculation complete"
return result
print("Function with parameters local variables:", calculate.__code__.co_nlocals)
Function with parameters local variables: 4
Key Points
- Function parameters are counted as local variables
- Variables assigned inside the function are local variables
- The
co_nlocalsattribute counts all local variables, including parameters - Empty functions or functions with only
passhave zero local variables
Conclusion
Use the __code__.co_nlocals attribute to find the number of local variables in any Python function. This includes both function parameters and variables assigned within the function scope.
