Should I use `app.exec()` or `app.exec_()` in my PyQt application?

PythonQtPython 3.xPyqtPyqt5

Python Problem Overview


I use Python 3 and PyQt5. Here's my test PyQt5 program, focus on the last 2 lines:

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys

class window(QWidget):
def __init__(self,parent=None):
	super().__init__(parent)
	self.setWindowTitle('test')
	self.resize(250,200)

app=QApplication(sys.argv)
w=window()
w.show()
sys.exit(app.exec())
#sys.exit(app.exec_())

I know exec is a language keyword in Python. But code on Official PyQt5 Documentation (specifically the Object Destruction on Exit part). I see that example shows use of app.exec() which confuses me.

When I tested it on my machine. I found there is no any visible difference from my end. Both with and without _ produces the same output in no time difference.

My question is:

  • Is there anything wrong going when I use app.exec()? like clashing with Python's internal exec? I suspect because both exec's are executing something.
  • If not, can I use both interchangeably?

Python Solutions


Solution 1 - Python

That's because until Python 3, exec was a reserved keyword, so the PyQt devs added underscore to it. From Python 3 onwards, exec is no longer a reserved keyword (because it is a builtin function; same situation as print), so it made sense in PyQt5 to provide a version without an underscore to be consistent with C++ docs, but keep a version with underscore for backwards compatibility. So for PyQt5 with Python 3, the two exec functions are the same. For older PyQt, only exec_() is available.

Solution 2 - Python

On the question of whether to prefer one over the other: using exec_ means you have one less thing to worry about if you ever decide to add support for PyQt4 and/or Python >= 2.6, and want to maintain a single code-base.

Solution 3 - Python

As of PyQt 6, app.exec_() is no longer supported, only app.exec() is.

Hence, when building new apps I only use the latter.

https://www.riverbankcomputing.com/static/Docs/PyQt6/pyqt5_differences.html?highlight=pyqt5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsocketView Question on Stackoverflow
Solution 1 - PythonOliverView Answer on Stackoverflow
Solution 2 - PythonekhumoroView Answer on Stackoverflow
Solution 3 - PythonericView Answer on Stackoverflow