Skip to content

Mypy subclass/intersection issue on 1.15.0 #18912

Description

@gandhis1

This code filters using an isinstance call to try to find objects that fit the profile of both Foo and Bar:

fromabcimportABCfromcollections.abcimportSequenceclassFoo(ABC):
passclassBar(ABC):
passclassBaz(ABC):
passclassFooBar(Foo, Bar):
passclassFooBaz(Foo, Baz):
passdefmy_func(foos: list[Foo]) ->Sequence[Foo]:
my_list= []
forfooinfoos:
ifnotisinstance(foo, Bar):
continuemy_list.append(foo)
returnmy_listfoos= [FooBar(), FooBaz()]
my_func(foos)

This code does not fail on Mypy 1.14.1:

https://mypy-play.net/?mypy=1.14.1&python=3.12&gist=7b5be66ab0fb3f04d15a99317ef21a7d

But it does fail on Mypy 1.15:

main.py:24: error: Argument 1 to "append" of "list" has incompatible type "__main__.<subclass of "Foo" and "Bar">1"; expected "__main__.<subclass of "Foo" and "Bar">" [arg-type]
Found 1 error in 1 file (checked 1 source file)

https://mypy-play.net/?mypy=1.15.0&python=3.12&gist=7b5be66ab0fb3f04d15a99317ef21a7d

Originally posted by @gandhis1 in python/typing#1968

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions