Python 3自动条件导入? [英] Python 3 automatic conditional import?

查看:64
本文介绍了Python 3自动条件导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好方法可以根据某个变量值导入不同的模块?
我的例子:

Is there any nice way to import different modules based on some variable value? My example:

我有一个包含不同模块的文件夹:

I have a folder with different modules:


  • module_a.py

  • module_b.py

在其他一些我想要的python文件中导入基于某个配置值的module_a或module_b:

And in some other python file i want to import either module_a or module_b based on some config value:

if configVal == 'a':
    import module_a
elif configVal == 'b':
    import module_b

是否有一些避免使用if-elifs的方法?

Is there some way to avoid using if-elifs? So somehow automatically?

like:

@conditionalImport(configVal)
import module_

还是更聪明的东西?

推荐答案

您可以使用 __ import __ 内置函数来将模块名称声明为字符串。

You can use the __import__ builtin to be able to state the module name as a string.

这样,您可以对模块名称执行常规的字符串操作:

In that way you can perform normal string operations on the module name:

module = __import__("module_{}".format(configVal))

这篇关于Python 3自动条件导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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