Making my code compatible with PyQt5/6 and PySide2/6, I wrote
if not hasattr(QtCore.QDateTime, 'toPython'): # fix for PyQt5/6
QtCore.QDateTime.toPython = QtCore.QDateTime.toPyDateTime
Run with PyQt5 or PyQt6, this resulted in
TypeError: toPyDateTime(self): first argument of unbound method must have type 'QDateTime'
when the function gets called:
QtCore.QDateTime.currentDateTime().toPython()
But if I change the call into
QtCore.QDateTime.toPython(QtCore.QDateTime.currentDateTime())
there is no error.
However, when I change the first piece of code to
if not hasattr(QtCore.QDateTime, 'toPython'): # fix for PyQt5/6
QtCore.QDateTime.toPython = lambda self: QtCore.QDateTime.toPyDateTime(self)
everything works fine whatever way I call toPython function. Why do I need the lambda expression here at all?
Added. To explain the behavior I'd expect, there is a piece of simple code:
class A:
def __init__(self) -> None:
print(f'make A ({hex(id(self))})')
def foo(self) -> None:
print(f'A ({hex(id(self))}) foo')
class B:
def __init__(self) -> None:
print(f'make B ({hex(id(self))})')
B.bar = A.foo
b: B = B() # prints “make B (0x7efc04c67f10)” (or another id)
B.bar(b) # prints “A (0x7efc04c67f10) foo” (same id, no error)
b.bar() # same result as before, no error
On the contrary, the following code doesn't work:
from PyQt6.QtCore import QDateTime
QDateTime.toPython = QDateTime.toPyDateTime
t: QDateTime = QDateTime.currentDateTime()
QDateTime.toPython(t) # no error
t.toPython() # raises TypeError