Conditional module importing in Python

风格不统一 提交于 2019-12-08 13:56:18

问题


I'm just trying out Maya 2017 and seen that they've gone over to PySide2, which is great but all of my tools have import PySide or from PySide import ... in them.

The obvious solution would be to find/replace import PySide to import PySide2 and hope everything still works after that, but I'd still like to be able to support older versions of Maya.

My idea was to have a single line solution to find/replace like:

import (PySide2 if "PySide2" in sys.modules else PySide)

But this returns: Error: invalid syntax

Does anyone have any ideas for an alternative to this? I'd like to try and keep it on a single line so it's an easy replacement for when I've got conditions like:

from PySide import QtCore, QtGui

Thank you!


回答1:


You could except the ImportError exception:

try:
    from Pyside2 import QtCore, QtGui

except ImportError:
    from PySide import QtCore, QtGui

Alternatively, you can use the importlib module:

import importlib
import sys

PySide = importlib.import_module('Pyside2' if 'Pyside2' in sys.modules else 'PySide')



回答2:


@user312016's answer worked nicely for "import" situations but less well for "from PySide import..." conditions. I ended up adding the following to my startup script which re-pathed everything nicely.

import sys
sys.modules['PySide'] = sys.modules['PySide2'] if 'PySide2' in sys.modules else sys.modules['PySide']
sys.modules['shiboken'] = sys.modules['shiboken2'] if 'shiboken2' in sys.modules else sys.modules['shiboken']


来源:https://stackoverflow.com/questions/40974449/conditional-module-importing-in-python

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