Python 3 automatic conditional import?

喜夏-厌秋 提交于 2020-01-26 00:58:13

问题


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

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

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

like:

@conditionalImport(configVal)
import module_

Or something clever?


回答1:


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



回答2:


As a matter of fact,we often use if else or try catch statement to write Python2/3 compatible code or avoid import errors.This is very common.

if sys.version_info[0] > 2:
    xrange = range

Or use try catch to raise exception.After modules that have been renamed, you can just import them as the new name.

try:
    import mod
except ImportError:
    import somemodule as mod

But it's bad practice to use an external script to make your script work.It is unusual to depend on external script to import modules in Python.




回答3:


It's normal to use if/try,except for import

for example

import sys
if sys.version_info > (2, 7):
    import simplejson as json
else:
    import json


来源:https://stackoverflow.com/questions/42576832/python-3-automatic-conditional-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!