Safely check for PyQt or PySide, without importing submodules Parameters ---------- api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault'] Which module to check for Returns ------- True if the relevant module appears to be importable
(api)
| 100 | |
| 101 | |
| 102 | def has_binding(api): |
| 103 | """Safely check for PyQt or PySide, without importing |
| 104 | submodules |
| 105 | |
| 106 | Parameters |
| 107 | ---------- |
| 108 | api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault'] |
| 109 | Which module to check for |
| 110 | |
| 111 | Returns |
| 112 | ------- |
| 113 | True if the relevant module appears to be importable |
| 114 | """ |
| 115 | # we can't import an incomplete pyside and pyqt4 |
| 116 | # this will cause a crash in sip (#1431) |
| 117 | # check for complete presence before importing |
| 118 | module_name = { |
| 119 | QT_API_PYSIDE: "PySide", |
| 120 | QT_API_PYSIDE2: "PySide2", |
| 121 | QT_API_PYSIDE6: "PySide6", |
| 122 | QT_API_PYQT: "PyQt4", |
| 123 | QT_API_PYQTv1: "PyQt4", |
| 124 | QT_API_PYQT_DEFAULT: "PyQt4", |
| 125 | QT_API_PYQT5: "PyQt5", |
| 126 | QT_API_PYQT6: "PyQt6", |
| 127 | } |
| 128 | module_name = module_name[api] |
| 129 | |
| 130 | import importlib |
| 131 | |
| 132 | try: |
| 133 | # importing top level PyQt4/PySide module is ok... |
| 134 | mod = __import__(module_name) |
| 135 | # ...importing submodules is not |
| 136 | |
| 137 | for check in ("QtCore", "QtGui", "QtSvg"): |
| 138 | if importlib.util.find_spec("%s.%s" % (module_name, check)) is None: |
| 139 | return False |
| 140 | |
| 141 | # we can also safely check PySide version |
| 142 | if api == QT_API_PYSIDE: |
| 143 | return check_version(mod.__version__, "1.0.3") |
| 144 | else: |
| 145 | return True |
| 146 | |
| 147 | except ModuleNotFoundError: |
| 148 | try: |
| 149 | from importlib import machinery |
| 150 | |
| 151 | # importing top level PyQt4/PySide module is ok... |
| 152 | mod = __import__(module_name) |
| 153 | |
| 154 | # ...importing submodules is not |
| 155 | loader_details = (machinery.ExtensionFileLoader, machinery.EXTENSION_SUFFIXES) |
| 156 | submod_finder = machinery.FileFinder(mod.__path__[0], loader_details) |
| 157 | submod_check = ( |
| 158 | submod_finder.find_spec("QtCore") is not None |
| 159 | and submod_finder.find_spec("QtGui") is not None |
no test coverage detected