Is there a nice way to switch between 2 different packages providing the same APIs?

Mark Summerfield m.n.summerfield at googlemail.com
Thu Jul 5 08:57:53 EDT 2018


For GUI programming I often use Python bindings for Qt.

There are two competing bindings, PySide and PyQt.

Ideally I like to have applications that can use either. This way, if I get a problem I can try with the other bindings: if I still get the problem, then it is probably me; but if I don't it may be an issue with the bindings.

But working with both means that my imports are very messy. Here's a tiny example:

if PYSIDE: # bool True -> Use PySide; False -> Use PyQt5
    from PySide2.QtCore import Qt
    from PySide2.QtGui import QIcon
    from PySide2.QtWidgets import (
        QDialog, QFrame, QGridLayout, QLabel, QLineEdit, QPushButton,
        QVBoxLayout)
else:
    from PyQt5.QtCore import Qt
    from PyQt5.QtGui import QIcon
    from PyQt5.QtWidgets import (
        QDialog, QFrame, QGridLayout, QLabel, QLineEdit, QPushButton,
        QVBoxLayout)

The PYSIDE constant is imported from another module and is used for all .py files in a given project so that just by changing PYSIDE's value I can run an entire application with PySide2 or with PyQt5.

But I'd really rather just have one lot of imports per file.

One obvious solution is to create a 'Qt.py' module that imports everything depending on the PYSIDE switch and that I then use in all the other .py files, something like this:

from Qt.QtCore import Qt
from Qt.QtGui import QIcon
... etc.

But I'm just wondering if there's a nicer way to do all this?


More information about the Python-list mailing list