[PyQt] PyQt/PyCharm/PEP problem with PyQt types

Phil Thompson phil at riverbankcomputing.com
Wed Nov 22 09:59:33 GMT 2017


On 22 Nov 2017, at 9:38 am, J Barchan <jnbarchan at gmail.com> wrote:
> 
> Thank you both, for the same solution.  I had noticed the Union[QWidget, None] construct and wondered if that was the only way/what I'm supposed to do in Python.  But it raises two questions, and only solves one of the two problems:
> 
> 1. I am "surprised" at the need to do this from Python every time an object might have value None.  It's "cumbersome" compared to the way NULL/0 is handled from C++, where it's always an acceptable value for any Object* parameter/return value.  Do you guys really write that for every place None is acceptable?
> 
> However, even if I find it "ugly", I agree I can use that for my own functions, e.g. a return value.  I can use this for the first of my examples, only.
> 
> 2. The problem is unsolved where a PyQt function accepts/returns None.  The second example I gave is calling QWidget.setParent(None).  The declaration of this in QtWidgets.pyi is:
>     def setParent(self, parent: 'QWidget') -> None: 
> Following your solutions, this ought to have been:
>     def setParent(self, parent: typing.Union['QWidget', None]) -> None:
> But the problem is that it isn't defined like that in the .pyi, and I can't help that.  And it's not just that function, it's lots of others too which accept or return None, so this issue keeps arising in my calling code.  Was it PyQt's job to recognise this and generate a different declaration or what?

No. That would require manually going through every call in the API to check whether NULL was a valid value for each pointer argument.

> Given where we are, I don't see any way of avoiding the warning when calling such a PyQt function with None, do you?

IMHO type hints are a massive missed opportunity. They seem to be designed for one purpose, ie. to support a particular form of code analysis (and not to provide API information to IDEs). The fact that you cannot formally describe all APIs that you can implement shows to me that the design is broken.

Phil


More information about the PyQt mailing list