Re: importing modules in c

Mark Lutz (mlutz@KaPRE.COM)
Mon, 12 Sep 1994 17:16:30 +0700

> I have the following code in c:
>
> else if ((module_ = import_module(name)) == NULL)
> return;
>
> run_command("print vars()");
>
> char buf[200];
> sprintf(buf,"import %s",name);
> run_command(buf);
> run_command("print vars()");
>
> Can someone explain into which name space the first import_module loads the
> new module?

None. It only gets added to the global sys.modules module list.

The short story...
import_module() only loads the module and stores it on sys.modules;
in your code, the resulting module object gets ignored, instead of
being inserted into any other module's dictionary. import_module()
only does half the job of an 'import' statement.

The long story...
When Python compiles an 'import' statement, it generates both an IMPORT_NAME
and a STORE_NAME op-code. At run-time, the IMPORT_NAME calls import_module(),
which returns a module object that gets pushed on the stack; the STORE_NAME
then pop's the module and inserts it into the current scope's dictionary
(the one containing the 'import' statement).

You're missing the STORE_NAME functionality-- the module gets loaded and put
on sys.modules, but isn't inserted into any enclosing scope's dictionary.
The run_command() form works, because it causes the string to get compiled
(which makes the STORE_STRING), and runs it in the scope of __main__
automatically. See Python/pythonrun.c for more details.

If you really want to import the module into __main__, you're probably best
off using the run_command() form above. There's lots of other tricks you
can do; for example, you can fetch the module from 'sys.modules', get a
module's scope and insert the import_module() result there manually, etc.
But it's not clear what your goal is from the above.

Mark Lutz