使用 __init__.py 加载动态 python 模块时出现问题
我正在尝试执行一个 __init__.py
来加载模块并实例化动态内部同名类。 这样的文件树
importer/
__init__.py # The file i'm writing
asd.py # It contains class asd
bsd.py # It contains class bsd
使用像And __init__.py
importername=__name__
def load(modname,paramlist = []):
if modname in globals():
print 'Module %s already loaded.' % (modname)
else:
imported_mod = __import__(importername + '.' + modname, fromlist = ["*"])
try:
globals()[modname]=getattr(imported_mod,modname)(*paramlist)
except Exception, e:
print 'Module %s not loaded: %s.' % (modname, e)
,如果我运行
import importer
importer.load('asd')
print importer.asd.name
'ASD!'
它就像一个魅力,但如果我运行
from importer import *
load('asd')
print asd.name
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'asd' is not defined
我可以以某种方式修复它吗?谢谢。
I'm trying to do an __init__.py
that load module and instantiate dinamically internal namesake class. With a file tree like
importer/
__init__.py # The file i'm writing
asd.py # It contains class asd
bsd.py # It contains class bsd
And __init__.py
with
importername=__name__
def load(modname,paramlist = []):
if modname in globals():
print 'Module %s already loaded.' % (modname)
else:
imported_mod = __import__(importername + '.' + modname, fromlist = ["*"])
try:
globals()[modname]=getattr(imported_mod,modname)(*paramlist)
except Exception, e:
print 'Module %s not loaded: %s.' % (modname, e)
If I run
import importer
importer.load('asd')
print importer.asd.name
'ASD!'
It works like a charm, but if I run
from importer import *
load('asd')
print asd.name
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'asd' is not defined
Can I fix it in some way? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python 中不存在真正的全局性。当您在 importer/__init__.py 中使用 globals() 时,您正在访问模块的名称空间。您的第二个非工作示例是将“asd”添加到导入器,而不是您的测试模块。
你能做的最好的就是修改导入器,这样你就可以这样做:
但正如托马斯·K所建议的:这有点奇怪,也许有一种更简单的方法来解决你的问题?
There is no such thing as truly global in Python. When you use globals() in
importer/__init__.py
, you are accessing the module's namespace. Your second non-working sample is adding 'asd' to importer, not to your test module.The best you could is modify importer so you could do:
But as Thomas K suggests: this is kind of odd, perhaps there's a simpler way to solve your problem?