[C++-sig] Importing and internal modules
Ravi
lists_ravi at lavabit.com
Mon Sep 29 23:07:58 CEST 2008
On Monday 29 September 2008 15:20:06 Peter LaDow wrote:
> The scriptable part is a module. It exposes a set of functions, so
> I'd really like to just import that module, and not execute it. So, I
> do the following:
[snip]
> // Import "foo"
> bp::exec("from foo import *", globals, globals);
>
> // Import the scriptable code
> bp::exec("from script import *", globals, globals);
>
> And here's an example of a script I am trying to import:
>
> def bar1():
> foo1()
> print "Called bar1!"
[snip]
> Now, the import for this fails with:
>
> NameError: global name 'foo1" is not defined
>
> Unless I put "from foo import *" at the top of the script. I want the
> 'foo' module already imported into the script. That's the point of
> the first of the imports.
Think about how this would work in pure python. When you import a module X,
all modules/functions X depends on must be explicitly imported in X.py. You
cannot import Y in the global interpreter namespace and somehow expect to
inject the contents of X into Y even if X has already been imported into the
global namespace. So what you are trying to do is impossible even in the pure
python case. Why would you expect it to work here?
Example:
foo.py
def foo():
print "foo"
bar.py
# import foo <-- note that this is commented out
def bar():
foo()
main.py
from foo import *
import bar
bar.bar() # <-- you will get a NameError here!
That said, you could inject the contents of foo into the dictionary of bar,
but you will run into subtle problems later. Try prototyping this in pure
python before attempting this from an extension module.
Regards,
Ravi
More information about the Cplusplus-sig
mailing list