Python中的动态模块加载范围

时间:2010-11-21 19:22:12

标签: python dynamic module scope

当我运行以下示例时:

def a():
    exec('import math')
    b()

def b():
    print math.cos(90)

a()

我收到以下错误: NameError:未定义全局名称'math'

我要做的是从a()函数中动态加载一些模块 并在函数b()

中使用它们

我希望b()的观点尽可能无缝。这意味着,我不想在()中使用_ _ import _ _加载模块并传递对b()函数的引用,实际上b()的函数签名仍然是必须的:b()

有没有办法做这个家伙? 谢谢!

2 个答案:

答案 0 :(得分:2)

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()

答案 1 :(得分:2)

对帖子发表评论:如果想加载模块运行时,请在需要的地方加载:

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)