[Q] module name available in 'from ... import ...' statement

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Apr 30 21:02:14 EDT 2007


En Mon, 30 Apr 2007 20:19:54 -0300, kwatch <kwatch at gmail.com> escribió:

> Could you teach me the condition of module name which is available
> in 'from ... import ...' statement?
>
> The goal what I want to do is to create a module by 'new' module
> and specify that module name in 'from ...' statement.

You can create the module with imp.new_module, populate it, and then  
insert it inside sys.modules:

py> from imp import *
py> m = new_module("foo")
py> m
<module 'foo' (built-in)>
py> m.a = 1
py> def test():
...   print "Function test inside foo module"
...
py> m.test = test
py> import sys
py> sys.modules["foo"]=m
py> m
<module 'foo' (built-in)>
py> foo
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
py> import foo
py> foo.test()
Function test inside foo module

But, why do you want to do this exactly?

-- 
Gabriel Genellina




More information about the Python-list mailing list