如何在将模块名称指定为函数参数的函数中创建(全局)Python 模块?

How can a (global) Python module be created within a function with the module name specified as an argument of the function?

我想在函数中创建一个全局模块对象,并将模块名称指定为函数的参数。我试图通过以下方式做到这一点:

import imp

def function1(moduleLocalName):
    exec("global " + moduleLocalName)
    moduleString = "bar = 3"
    exec(moduleLocalName + " = imp.new_module(\"" + moduleLocalName + "\")")
    exec moduleString in globals()[moduleLocalName].__dict__

function1("foo")
print(foo.bar)

模块似乎在函数范围内创建成功,但在函数范围外不可用。请注意,我不想简单地 return 函数中的模块对象,将其设置为现有的全局对象;我想在 函数中创建全局模块对象 。我该怎么做?

最佳:

import sys, types

def function1(moduleLocalName):
    m = types.ModuleType(moduleLocalName)
    setattr(m, 'bar', 3)
    sys.modules[moduleLocalName] = m
    return m

foo = function1('foo')

任何其他模块现在都可以 import foo,因为我们将其固定在 sys.modules

重要教训:不要使用exec。你真的不需要它。如果你认为你需要它,你很可能是错的。