Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you easily select between PyQt or PySide at runtime?

I would like to do something like this in one source file, QT.py:

import sys
import PyQt4

sys.modules["Qt"] = PyQt4

Then import this file in the other source files, and use it like this:

import QT
from Qt.QtCore import *

So I can change from PyQt4 to PySide in QT.py without touching all the source files (with a possibly ugly sed script) These modules are mostly API compatibile and I would like to test them both. Is there an easy way to do this? (Because the ways I tried are not working)

Maybe the I need imp module, but it seems too low level.

Any ideas?

like image 460
John T. Brown Avatar asked Nov 08 '11 14:11

John T. Brown


1 Answers

Use an import hook:

def set_qt_bindings(package):
    if package not in ('PyQt4', 'PySide'):
        raise ValueError('Unknown Qt Bindings: %s' % package)
    import __builtin__
    __import__ = __builtin__.__import__
    def hook(name, globals=None, locals=None, fromlist=None, level=-1):
        root, sep, other = name.partition('.')
        if root == 'Qt':
            name = package + sep + other
        return __import__(name, globals, locals, fromlist, level)
    __builtin__.__import__ = hook

if __name__ == '__main__':

    import sys

    if len(sys.argv) > 1:

        set_qt_bindings(sys.argv[-1])

        import Qt
        print Qt

        from Qt import QtCore
        print QtCore

        from Qt.QtGui import QWidget
        print QWidget

Output:

$ python2 test.py PySide
<module 'PySide' from '/usr/lib/python2.7/site-packages/PySide/__init__.py'>
<module 'PySide.QtCore' from '/usr/lib/python2.7/site-packages/PySide/QtCore.so'>
<type 'PySide.QtGui.QWidget'>
$ python2 test.py PyQt4
<module 'PyQt4' from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'>
<module 'PyQt4.QtCore' from '/usr/lib/python2.7/site-packages/PyQt4/QtCore.so'>
<class 'PyQt4.QtGui.QWidget'>
like image 103
ekhumoro Avatar answered Oct 12 '22 00:10

ekhumoro