Type hints for subclasses
Answered
I was wondering if there is any elegant solution to the following problem:
I have a class A and its subclass B. A has a method that returns an instance of class A (a type hint in the docstring indicates that). Now, the subclass should inherit the method and return an instance of class B. But PyCharm now thinks that, when I use b.function(), its return type is A.
Is there any way to inherit and adapt the type hint accordingly? The way I'm solving it now is to override the method and write a new docstring, but this is a terrible solution.
Thanks a lot!
Please sign in to leave a comment.
Hi Manuel,
Would it be possible to provide some simple sample code to demonstrate the problem?
Is it something similar to https://youtrack.jetbrains.com/issue/PY-15743?
Hi Sergey,
Yes, it is somehow similar indeed (also to https://youtrack.jetbrains.com/issue/PY-4813). What they were asking for would be very convenient too..
So my problem is the following:
The problem is that the return type doesn't get "inherited". This is the version without explicit type hints, but it is basically the same outcome.
What I am looking for is something like the following:
So that the subclass realises that it returns an instance of its own class. (The unresolved attribute warning disappeared here because the unknown __thisclass__ is translated to type "Any" by PyCharm.)
Any suggestions? (here's the code btw. https://www.dropbox.com/s/o4rbjxexl9h1g5p/demo.py?dl=0)
Thanks for taking a look and for a sample code!
Hm, looks just fine on my side:
What is your PyCharm version?
That's strange. I'm running the latest version on Mac:
PyCharm 2018.2.4 (Professional Edition)
Build #PY-182.4505.26, built on September 19, 2018
JRE: 1.8.0_152-release-1248-b8 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Do you have any custom plugins installed? If yes, try disabling them and see if problem remains.
Try starting with default settings by renaming/removing the folder https://intellij-support.jetbrains.com/hc/en-us/articles/206544519.
Please let me know the result.
I get the same issue, I tried removing the folder as you said, and it seemed to work. But it asked me to configure my environment, which seems important, so I did so and I get the Unresolved attribute reference again.
@Dwarnke
Which step triggered this issue when you were configuring your environment?
Sorry, Project Interpreter. When I configure the Project Interpreter it stops working. The project interpreter I am using is coming from a miniconda environment. I have tried the miniconda base Python 3.7 environment, as well as a Python 3.6 and a Python 3.7 environment I have set up. They create the same problem. Typing was around in 3.5 so it should work.
@Dwarnke
Do you have a minimal code snippet for reproducing?
Thanks!
I filed a bug to our issue tracker https://youtrack.jetbrains.com/issue/PY-40498, please upvote and feel free to leave comments.