Why are some people cautious about using sender()
in Qt programming? The typical answer is that it violates the principle of modularity of code. From the Qt documentation about pitfalls in PySide:
If you want to get the object that emitted a signal, you can do so using QtCore.QObject.sender(), although you should really think twice before using it (see the API docs of QObject for details). If you really, really decide that you have to use it, be aware that right now, you cannot call it as a static method, but only from within a QObject slot.
As a new PySide programmer, I wouldn't consider using sender
in anything but a slot, so the second concern seems almost moot.
The first reason suggests examining the API of the doc. Let's look at that. From the API docs for sender:
This function violates the object-oriented principle of modularity.
This caveat is also mentioned in Summerfield's book on PyQt, where he writes
Some programmers don’t like using
sender()
because they feel that it isn’t good object-oriented style.
That's all he says.
What makes sender
particularly non-modular compared to the rest of the standard practices in using PyQt/PySide/Qt? In PySide we are constantly invoking things like internalPointers in our model/view frameworks, or sneaking arguments to use in methods by making them attributes of self
(effectively treating them as global variables). These and other such practices seem to technically violate modularity, and seem to be ubiquitous in GUI programming.
So why do people think sender
deserves to be singled out as especially worrisome wrt modularity? Or perhaps equivalently, what is so modular about Qt programming anyway?
Overall, sender
seems like an extremely useful, simple method. It is easier to use and teach others to use than things like partial
functions or lambda
expressions or QSignalMapper
. So I can see the upside of using sender
, and frankly have little grasp of the downsides that have merited their inclusion in official Qt documentation.