Python program to find number of local variables in a function

Given a Python program, task is to find the number of local variables present in a function.

Examples:

Input : a = 1
        b = 2.1
        str = 'GeeksForGeeks'
    
Output : 3

We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result.

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Implementation of above approach
  
# A function containing 3 variables 
def fun():
    a = 1
    str = 'GeeksForGeeks'
  
  
# Driver program
print(fun.__code__.co_nlocals)

chevron_right


Output:



2

 
Code #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to find number of
# local variables in a function
  
# A function containing no variables 
def geek():
    pass
  
# A function containing 3 variables 
def fun():
    a, b, c = 1, 2.25, 333
    str = 'GeeksForGeeks'
  
# Driver program
print(geek.__code__.co_nlocals)
print(fun.__code__.co_nlocals)

chevron_right


Output:

0
4

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.