Unexpected behavior on overloaded methods with annotated self
of a generic class
#18597
Labels
bug
mypy got something wrong
Bug Report
Lately I discover that partial specialization is allowed by mypy by annotating
self
in the methods of a generic class, as shown in some examples in the docs (https://mypy.readthedocs.io/en/stable/more_types.html#advanced-uses-of-self-types), which is very nice. Then I went down trying to combine this with overloaded methods, but unfortunately it doesn't behaved as I expected. This got me wondering if it is a bug or if my implementation is lacking something. Any help understanding or fixing this would be very appreciated.There is a few issues regarding this topic (e.g. #5320 and #10517), but they were facing slighted different problems and they are already closed/solved.
In summary, in the following example it seems that the second overload (
def bar(self: Foo[bool], a: bytes) -> None:
) is never reached, and there is some gotchas while callingself.bar
from another method ofFoo
.To Reproduce
Playground link: https://mypy-play.net/?mypy=latest&python=3.10&gist=466d7197598df9ca65258d8b7aca2c84
Expected Behavior
Among all the things a bit strange (to me) happening here, my main expectation is that mypy shoud have flagged
Foo(True).bar(1)
, because it falls under thedef bar(self: Foo[bool], a: bytes) -> None
overload.This tells me that the overload strategy is not working as I expected.
I'm also not sure the expected behavior of calling
bar
from other methods, such as what happens insideFoo.call_bar
. At least I would expect bothself.bar(1)
andself.bar(b'ok')
to fail or succeed, not only one.One thing though regarding this last case: if I annotate
self: Foo
incall_bar
, none of then are flagged -- I guess its becauseT
will beAny
so the call will fallback to the not-overloadedbar
which accepts both types. I wonder if this would be the correct approach?Actual Behavior
Mypy output:
Your Environment
mypy.ini
(and other config files): N/AThe text was updated successfully, but these errors were encountered: