如何从函数中进行全局导入?

Gio*_*lia 55 python import module python-module

我担心这是解决问题的一种混乱方式,但......

假设我想根据某些条件在Python中进行一些导入.

出于这个原因,我想写一个函数:

def conditional_import_modules(test):
    if test == 'foo':
        import onemodule, anothermodule
    elif test == 'bar':
        import thirdmodule, and_another_module
    else:
        import all_the_other_modules
Run Code Online (Sandbox Code Playgroud)

现在我如何才能在全球范围内提供导入的模块?

例如:

conditional_import_modules(test='bar')
thirdmodule.myfunction()
Run Code Online (Sandbox Code Playgroud)

Rom*_*huk 64

导入的模块只是变量 - 绑定到某些值的名称.因此,您只需要导入它们并使用global关键字使其全局化.

例:

>>> math
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> def f():
...     global math
...     import math
...
>>> f()
>>> math
<module 'math' from '/usr/local/lib/python2.6/lib-dynload/math.so'>
Run Code Online (Sandbox Code Playgroud)

  • 你确定这是合法的吗?文档(https://docs.python.org/2/reference/simple_stmts.html#grammar-token-global_stmt)说"全局语句中列出的名称不能定义为形式参数或for循环控制目标,类定义,函数定义或import语句." 然后它说这不是针对cpython强制执行的,但是你不应该这样做. (4认同)

bad*_*zil 10

您可以在这样的函数中使导入全局:

def my_imports(module_name):
    globals()[module_name] = __import__(module_name)
Run Code Online (Sandbox Code Playgroud)


raf*_*bie 7

我刚刚遇到了类似的问题,这是我的解决方案:

class GlobalImport:

    def __enter__(self):
        return self

    def __call__(self):
        import inspect
        self.collector = inspect.getargvalues(inspect.getouterframes(inspect.currentframe())[1].frame).locals

    def __exit__(self, *args):
        globals().update(self.collector)
Run Code Online (Sandbox Code Playgroud)

然后,在代码中的任意位置:

with GlobalImport() as gi:
    import os, signal, atexit, threading, _thread
    # whatever you want it won't remain local
    # if only 
    gi()
    # is called before the end of this block

# there you go: use os, signal, ... from whatever place of the module
Run Code Online (Sandbox Code Playgroud)


max*_*zig 5

您可以使用内置函数__import__有条件地导入具有全局范围的模块。

导入顶级模块(想想:)import foo

def cond_import():
  global foo
  foo = __import__('foo', globals(), locals()) 
Run Code Online (Sandbox Code Playgroud)

从层次结构导入(想想:)import foo.bar

def cond_import():
  global foo
  foo = __import__('foo.bar', globals(), locals()) 
Run Code Online (Sandbox Code Playgroud)

从层次结构和别名导入(想想:)import foo.bar as bar

def cond_import():
  global bar
  foo = __import__('foo.bar', globals(), locals()) 
  bar = foo.bar
Run Code Online (Sandbox Code Playgroud)