[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

On 05Jul2018 05:57, Mark Summerfield <m.n.summerfield at googlemail.com> wrote:
>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)
>    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?

My recollection is that the Qt names are pretty unique; they're grouped into 
QtCore and QtGui and so forth for organisational, conceptual and maintenance 
reasons, but generally don't conflct.  I tend to make a module like your 
"Qt.py" which doesn't have any hierarchy in its own namespace, so you get code 
like this:

  from Qt import Qt, QIcon, ...

I would call it something other than "Qt" though, to avoid conflict with 
PyQt5.QtCore.Qt etc. Maybe "myqt" or the like.

Your existing sample "if PYSIDE:" code should work directly, as all those names 
you import become simple flat names inside Qt (Qt.Qt, Qt.QIcon, Qt.QDialog, 

Cameron Simpson <cs at cskk.id.au>