Search code examples
pythoncythonpyside2

cython;pyside2;RecursionError: maximum recursion depth exceeded while calling a Python object


The following very simple code runs well: python tmpmain.py would give you a window with a Help menu, and Help->About would give you a message. But once I cythonized the tmp.py into an extension, and rename tmp.py to tmp.py.bak to make sure tmpmain.py calls the compiled extension, python tmpmain.py will cause the RecursionError: maximum recursion depth exceeded while calling a Python object. I have simplified the code as much as I can, hoping it may help debug. Any suggestion?

#tmpmain.py
from tmp import main
if __name__ == '__main__':
    main() 

and,

#tmp.py
from PySide2.QtWidgets import (QApplication,  QMainWindow, QMenu, QMessageBox)
 from PySide2.QtCore import Slot

class MainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__()
        self.setupHelpMenu()        


    def setupHelpMenu(self):
        helpMenu = QMenu("&Help", self)
        self.menuBar().addMenu(helpMenu)
        helpMenu.addAction("&About", self.about)

    @Slot()
    def about(self):
        QMessageBox.about(self, "About", "This is a demo")

import sys

def main():

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

The command to compile tmp.py is:

cythonize -X language_level=3 -i tmp.py

Solution

  • This is more of an unsatisfactory workaround than an answer:

    I have actually seen this problem before and posted the same unsatisfactory workaround as a comment. You need to wrap your function calls in a lambda function by changing the line:

    helpMenu.addAction("&About", self.about)
    

    to

    helpMenu.addAction("&About", lambda: self.about())
    

    I'm unclear why exactly this helps, but I'm posting the answer so for both the workaround and in the hope that this gives someone a clue where to start a proper diagnosis of the fault.