title: Checking if a Python function referenced anything out-of-scope
body: <p>I'm exploring what's possible to do in Python and recently came across this question: after running a function, is it possible to programmatically determine whether it has referenced anything out-of-scope? For example:</p>
  <pre><code>import module1
  
  y = 1
  
  def foo1(x):
      return y + x  # yes - it has referenced 'y' which is out of foo1 scope
  
  def foo2(x):
      return module1.function1(x)  # yes - it has referenced 'module1' which is out of foo2 scope
  
  def foo3(x):
      return x*x  # no - it has only referenced 'x' which is an input to foo3, so the code executed within the scope of foo3
  </code></pre>
  <p>Are there some reflection / analysis tools for this? Maybe this could be achieved with the 'trace' module  somehow?</p>