开发者

Dynamic Module loading scope in Python

When I run the following sample:

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

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

a()

I get the following error: NameError: global name 'math' is not defined

What I am trying to do is to dynamically load some modules from within the a() function and use them in function b()

I want it to be as seamless as possible fo开发者_运维知识库r the b()'s point of view. That means, I don't want to load the module with _ _ import _ _ in a() and pass a reference to the b() function, in fact it is mandatory that the b()'s function signature remains just this: b()

is there any way to do this guys? thanks!


Upon comments on the post: if want to load modules runtime, load where you need it:

def b():
  m = __import__("math")
  return m.abs(-1)

Answering to your question:

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)


One approach for Python 2.x would be:

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

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

a()

But I would generally recommend using __import__(). I don't know what you are actually trying to achieve, but maybe this works for you:

def a():
    global hurz
    hurz = __import__("math")
    b()

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

a()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜