Sage Gerard Sage Gerard - 2 months ago 8
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():
pass

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.

Answer

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

foo.__code__.co_nlocals

Demo:

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

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); [...]

Comments