[英]Dynamic Module loading scope in Python
当我运行以下示例时:
def a():
exec('import math')
b()
def b():
print math.cos(90)
a()
我收到以下错误: NameError:未定义全局名称'math'
我想要做的是从a()函数中动态加载一些模块并在函数b()中使用它们
我希望它与b()的观点尽可能无缝。 这意味着,我不想在()中使用_ _ import _ _加载模块并传递对b()函数的引用,实际上b()的函数签名仍然是必须的:b()
有没有办法做这个家伙? 谢谢!
Python 2.x的一种方法是:
def a():
exec 'import math' in globals()
b()
def b():
print math.cos(90)
a()
但我通常建议使用__import__()
。 我不知道你到底想要实现什么,但也许这适合你:
def a():
global hurz
hurz = __import__("math")
b()
def b():
print hurz.cos(90)
a()
对帖子发表评论:如果要加载模块运行时,请在需要的地方加载:
def b():
m = __import__("math")
return m.abs(-1)
回答你的问题:
def a():
if not globals().has_key('math'):
globals()['math'] = __import__('math')
def b():
"""returns the absolute value of -1, a() must be called before to load necessary modules"""
return math.abs(-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.