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>Yes, the associated code object accounts for all local names in the <code>co_nlocals</code> attribute:</p>

<pre><code>foo.__code__.co_nlocals
</code></pre>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; def foo():
...     a = 1
...     b = 2
...
&gt;&gt;&gt; foo.__code__.co_nlocals
2
</code></pre>

<p>See the <a href="https://docs.python.org/3/reference/datamodel.html"><em>Datamodel</em> documentation</a>:</p>

<blockquote>
  <p><em>User-defined functions</em></p>
  
  <p><em>[...]</em></p>
  
  <p><code>__code__</code>   The code object representing the compiled function body. </p>
  
  <p><em>Code objects</em></p>
  
  <p><em>[...]</em></p>
  
  <p>Special read-only attributes: <em>[...]</em> <code>co_nlocals</code> is the number of local variables used by the function (including arguments); <em>[...]</em></p>
</blockquote>

python metaprogramming