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

发布于 2021-01-29 18:40:39

我担心这是解决问题的麻烦方式,但是…

假设我想根据某些条件在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

现在如何使导入的模块全局可用?

例如:

conditional_import_modules(test='bar')
thirdmodule.myfunction()
关注者
0
被浏览
53
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    导入的模块只是变量-名称绑定到某些值。因此,您所需要做的就是导入它们,并使用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'>
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看