Is it possible to detect the number of local variables declared in a function?
<p>In a Python test fixture, is it possible to count how many local variables a function declares in its body?</p>

<pre><code>def foo():
    a = 1
    b = 2

Test.assertEqual(countLocals(foo), 2)
</code></pre>

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

<pre><code>def foo():
    a = 1
    b = 2

def bar():
    pass

Test.assertEqual(hasLocals(foo), True)
Test.assertEqual(hasLocals(bar), False)
</code></pre>

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

<p>To elaborate somewhat on @Martijn excellent answer, if you read the documentation for the <a href="https://docs.python.org/3/library/inspect.html" rel="nofollow">inspect â Inspect live objects</a> module, you can see that it allows for introspection of a wealth of data, including (as @Martijn noted) in the <code>code</code> type, the following attributes:</p>

<pre><code>co_names    tuple of names of local variables
co_nlocals  number of local variables
</code></pre>

python metaprogramming