Make 2-arg iter() return type match passed callable's return type#3326
Make 2-arg iter() return type match passed callable's return type#3326srittau merged 1 commit intopython:masterfrom wbolster:2-arg-iter-return-type
Conversation
This is a continuation of #3291, which was the initial fix for #3201. The 2-arg version of iter() turns a callable into an iterator. The changes made in #3291 introduce an Any return type for both the callable's return type and the iterator's type, while in reality the return type of the function is always the same as the iterator's type.
|
ping @srittau @utkarsh2102 who worked on and reviewed #3201/#3291. |
|
example: def a() -> Union[str, int]:
return ""
n: Union[str, int] = 1
reveal_type(iter(a, n))
# Revealed type is 'typing.Iterator[Union[builtins.str, builtins.int]]' (python-mypy)
reveal_type(iter(a, 1))
# Revealed type is 'typing.Iterator[Union[builtins.str, builtins.int]]' (python-mypy)
reveal_type(iter(a, "foo"))
# Revealed type is 'typing.Iterator[Union[builtins.str, builtins.int]]' (python-mypy)
reveal_type(iter(a, b"foo"))
# Revealed type is 'typing.Iterator[Union[builtins.str, builtins.int]]' (python-mypy)
def b() -> Optional[str]:
return ""
reveal_type(iter(b, None))
# Revealed type is 'typing.Iterator[builtins.str*]' (python-mypy)the only thing that seems ‘not strict enough’ seems the example above that passes a bytestring as a sentinel, which doesn't necessarily make sense since the function will never return a bytestring. however, the sentinel may still compare equal (2-arg |
|
thanks for the quick review, @srittau! as you can see, it took me some experiments to figure out the right approach. 🤯 i wasted some time trying to get rid of the |
This is a continuation of #3291, which was the initial fix for #3201.
The 2-arg version of iter() turns a callable into an iterator. The
changes made in #3291 introduce an Any return type for both the
callable's return type and the iterator's type, while in reality the
return type of the function is always the same as the iterator's type.