Modules and variable scopes
<p>I'm not an expert at python, so bear with me while I try to understand the nuances of variable scopes.</p>

<p>As a simple example that describes the problem I'm facing, say I have the following three files.</p>

<p>The first file is outside_code.py. Due to certain restrictions I cannot modify this file. It must be taken as is. It contains some code that runs an eval at some point (yes, I know that eval is the spawn of satan but that's a discussion for a later day). For example, let's say that it contains the following lines of code:</p>

<pre><code>def eval_string(x):
    return eval(x)
</code></pre>

<p>The second file is a set of user defined functions. Let's call it functions.py. It contains some unknown number of function definitions, for example, let's say that functions.py contains one function, defined below:</p>

<pre><code>def foo(x):
    print("Your number is {}!".format(x))
</code></pre>

<p>Now I write a third file, let's call it main.py. Which contains the following code:</p>

<pre><code>import outside_code
from functions import *
outside_code.eval_string("foo(4)")
</code></pre>

<p>I import all of the function definitions from functions.py with a *, so they should be accessible by main.py without needing to do something like functions.foo(). I also import outside_code.py so I can access its core functionality, the code that contains an eval. Finally I call the function in outside_code.py, passing a string that is related to a function defined in functions.py.</p>

<p>In the simplified example, I want the code to print out "Your number is 4!". However, I get an error stating that 'foo' is not defined. This obviously means that the code in outside_code.py cannot access the same foo function that exists in main.py. So somehow I need to make foo accessible to it. Could anyone tell me exactly what the scope of foo currently is, and how I could extend it to cover the space that I actually want to use it in? What is the best way to solve my problem?</p>

<p><code>foo</code> has been imported into main.py; its scope is restricted to that file (and to the file where it was originally defined, of course). It does not exist within outside_code.py.</p>

<p>The real <code>eval</code> function accepts locals and globals dicts to allow you to add elements to the namespace of the evaluted code. But you can't do anything if your <code>eval_string</code> doesn't already pass those on.</p>

python python-3.x