module name available in 'from ... import ...' statement
kwatch
kwatch at gmail.com
Mon Apr 30 22:42:32 EDT 2007
Thanks Carsten and Gabriel,
the answer is 'sys.modules'.
----------------------------------------
import sys, os
from path import sep # ImportError: No module named path
sys.modules['path'] = os.path
from path import sep # (no error)
----------------------------------------
I can now import from my module which is generated by 'new' module.
----------------------------------------
# create a module
import new
foo = new.module('foo')
foo.pi = 3.14159
foo.x2 = lambda x: 2*x
# register it to sys.modules
import sys
sys.modules['foo'] = foo
# import from that module
from foo import pi, x2
----------------------------------------
Great.
> Not that this can't be done, but why do you think you have to create
> this 'foo' module on the fly? What is the actual problem you're trying
> to solve?
I have a package which has several small modules and I want to
integrate them into a file, with keeping compatibility.
current:
mylib/
__init__.py
html.py
xhtml.py
xml.py
:
:
future:
mylib.py
--
regards,
kwatch
"Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Mon, 30 Apr 2007 20:19:54 -0300,kwatch<kwa... 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