Specifying self-type for first __init__
overload affects isinstance
type narrowing
#19221
Labels
bug
mypy got something wrong
topic-self-types
Types for self
topic-type-narrowing
Conditional type narrowing / binder
Uh oh!
There was an error while loading. Please reload this page.
Bug Report
I have a generic class with multiple
__init__
overloads. One of the__init__
overloads specifies the type ofself
in order to control what the type variable evaluates to for this overload.When I upgraded this code to Mypy 1.16, I started getting errors in a method that uses
isinstance
to check whether another object is an instance of the same class. I expectedif isinstance(other, A):
to narrow the type ofother
toA[Any]
, but it actually narrows to the self-type specified in the first__init__
overload, such asA[int]
.If I reorder the
__init__
overloads so the first overload does not specify a self-type, thenif isinstance(other, A):
seems to narrow toA[Any]
, orA[T]
in methods that take a union ofA[T]
and other types. This is the behavior I expected.With Mypy 1.15 and older, the behavior is different. Specifying a self-type for the first
__init__
overload causesif isinstance(other, A):
to narrow the type ofother
toNever
. I think this is why I didn't get any errors before upgrading to Mypy 1.16.Pyright doesn't complain about this code.
To Reproduce
Classes A and B are the same except for the order of the
__init__
overloads.https://mypy-play.net/?mypy=latest&python=3.12&gist=dae546cdc2f11d2f5bd582efa826e188
Expected Behavior
Actual Behavior
Mypy 1.16:
Mypy 1.15:
Your Environment
mypy.ini
(and other config files):strict=true
, but it's also reproducible with noneThe text was updated successfully, but these errors were encountered: