Note that there are some explanatory texts on larger screens.

plurals
  1. POPython __import__ parameter confusion
    text
    copied!<p>I'm trying to import a module, while passing some global variables, but it does not seem to work:</p> <p>File test_1:</p> <pre><code>test_2 = __import__("test_2", {"testvar": 1}) </code></pre> <p>File test_2:</p> <pre><code>print testvar </code></pre> <p>This seems like it should work, and print a 1, but I get the following error when I run test_1:</p> <pre><code>Traceback (most recent call last): File ".../test_1.py", line 1, in &lt;module&gt; print testvar NameError: name 'testvar' is not defined </code></pre> <p>What am I doing wrong?</p> <p><strong>EDIT:</strong></p> <p>As I commented later on, this is an attempt to replace the functions within a graphics library. Here is a sample program (that my teacher wrote) using that library:</p> <pre><code>from graphics import * makeGraphicsWindow(800, 600) ############################################################ # this function is called once to initialize your new world def startWorld(world): world.ballX = 50 world.ballY = 300 return world ############################################################ # this function is called every frame to update your world def updateWorld(world): world.ballX = world.ballX + 3 return world ############################################################ # this function is called every frame to draw your world def drawWorld(world): fillCircle(world.ballX, world.ballY, 50, "red") ############################################################ runGraphics(startWorld, updateWorld, drawWorld) </code></pre> <p>Note that this code is designed such that people who have never (or almost never) seen ANY code before (not just python) would be able to understand with little effort.</p> <p>Example for rewriting the function:</p> <p>Original code:</p> <pre><code>def drawPoint(x, y, color=GLI.foreground): GLI.screen.set_at((int(x),int(y)), lookupColor(color)) </code></pre> <p>Injected code:</p> <pre><code># Where self is a window (class I created) instance. def drawPoint(x, y, color = self.foreground): self.surface.set_at((int(x), int(y)), lookupColor(color)) </code></pre> <p>I guess my real question is: how would I inject global functions/variables into an imported module before the module runs...?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload