Skip to content

Treat bool as equivalent to Literal[True, False] to allow better type inference #6113

Description

@ahmedsoe

Similar to this #6027, but more basic use case.

fromtypingimportCollection, Union, Listdeffoo(bar: Union[bool, Collection[int]]) ->Union[int, List[int]]:
ifbarisFalse: # or if not bar:return10ifbarisTrue:
return20# otherwise, bar must be a collection (list, tuple, ...)return [i*2foriinbar]
print(foo(True))
print(foo(False))
print(foo([1, 2, 3]))
print(foo((1, 2, 3,)))

Mypy is giving the error

error: Item "bool" of "Union[bool, Collection[int]]" has no attribute "__iter__" (not iterable)

But it should be able to infer that it can't be a bool?
using if / elif /else also gives the error.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions