Skip to content

How to properly type methods that return Generators with subclasses? #1036

Answered by erictraut
DanielNoord asked this question in Q&A
Discussion options

You must be logged in to vote

The problem is that Callable parameters are position-only, since they are nameless, but the method my_method that you are attempting to override accepts a parameter named param that can be specified as positional or as keyword. If you change my_method in Parent to accept position-only parameters, mypy will no longer generate an error.

def my_method(self, param: str, /) -> Generator["Parent", None, None]:
    ...

or

def my_method(self, __param: str) -> Generator["Parent", None, None]:
    ...

The error message provided by mypy is quite misleading and could be improved. By comparison, here's the error emitted by pyright:

Method "my_method" overrides class "Parent" in an incompatible manner
…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@DanielNoord
Comment options

@JelleZijlstra
Comment options

@erictraut
Comment options

Answer selected by DanielNoord
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants