如何从函数中进行全局导入? [英] How to make global imports from a function?

查看:104
本文介绍了如何从函数中进行全局导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心这是解决问题的麻烦方法,但是...

I fear that this is a messy way to approach the problem but...

让我们说我想根据某些条件在Python中进行一些导入.

let's say that I want to make some imports in Python based on some conditions.

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

For this reason I want to write a function:

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

现在如何使导入的模块在全球范围内可用?

Now how can I have the imported modules globally available?

例如:

conditional_import_modules(test='bar')
thirdmodule.myfunction()

推荐答案

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

Imported modules are just variables - names bound to some values. So all you need is to import them and make them global with global keyword.

示例:

>>> 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'>

这篇关于如何从函数中进行全局导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆