Sage Gerard Sage Gerard - 4 months ago 12
Python Question

Is it possible to detect the number of local variables declared in a function?

In a Python test fixture, is it possible to count how many local variables a function declares in its body?

def foo():
a = 1
b = 2

Test.assertEqual(countLocals(foo), 2)

Alternatively, is there a way to see if a function declares any variables at all?

def foo():
a = 1
b = 2

def bar():

Test.assertEqual(hasLocals(foo), True)
Test.assertEqual(hasLocals(bar), False)

The use case I'm thinking of has to do with validating user-submitted code.


Yes, the associated code object accounts for all local names in the co_nlocals attribute:



>>> def foo():
...     a = 1
...     b = 2
>>> foo.__code__.co_nlocals

See the Datamodel documentation:

User-defined functions


__code__ The code object representing the compiled function body.

Code objects


Special read-only attributes: [...] co_nlocals is the number of local variables used by the function (including arguments); [...]