Python | Detecting the number of local variables declared in a function

To calculate the number of local variables in a particular function we have a dedicated built-in function. Let us take a look at it

def addition_num(num1, num2):
  num1 += num2
  return num1
def subtraction_num(num1, num2):
  num1 -= num2
  return num1
def mul_num(num1, num2):
  num1 *= num2
  return num1
def division_num(num1, num2):
  num1 /= num2
  return num1
def default(num1, num2):
  return "Incorrect day"
switcher = {
    1: addition_num,
    2: subtraction_num,
    3: mul_num,
    4: division_num,
    
}
def switch(operation, num1, num2):
  return switcher.get(operation, default)(num1, num2)
print('''You can perform operation
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Module ''')
# Take input from user
choice = int(input("Select operation from 1,2,3,4 : "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print ("Output:",switch(choice, num1, num2))

print("The number of local variables in addition_num function are :",addition_num.__code__.co_nlocals)
print("The number of local variables in subtraction_num function are :",subtraction_num.__code__.co_nlocals)
print("The number of local variables in mul_num function are :",mul_num.__code__.co_nlocals)
print("The number of local variables in division_num function are :",division_num.__code__.co_nlocals)
print("The number of local variables in default function are :",default.__code__.co_nlocals)

Output:

You can perform operation
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Module 

Select operation from 1,2,3,4 : 1
Enter first number: 2
Enter second number: 3
Output: 5

The number of local variables in addition_num function are : 2
The number of local variables in subtraction_num function are : 2
The number of local variables in mul_num function are : 2
The number of local variables in division_num function are : 2
The number of local variables in default function are : 2

Explanation:

Here we simply used the code.co_nlocals to calculate the number of local variables in the particular function. All we have to do is add the name of the function at the beginning of the code.co_nlocals

Share:

Author: Ayush Purawr