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

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

问题描述

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

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

为此我想写一个函数:

def conditional_import_modules(test):如果测试 == 'foo':导入一个模块,另一个模块elif 测试 == 'bar':导入第三个模块和_another_module别的:导入 all_the_other_modules

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

例如:

conditional_import_modules(test='bar')第三个模块.myfunction()

解决方案

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

示例:

<预><代码>>>>数学回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中NameError: 名称 'math' 未定义>>>定义 f():... 全球数学... 导入数学...>>>F()>>>数学<来自'/usr/local/lib/python2.6/lib-dynload/math.so'的模块'math'>

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

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?

For example:

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

解决方案

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.

Example:

>>> 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天全站免登陆