8000 two-arg iter() with None sentinel does not remove ‘Optional’ · Issue #7371 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

two-arg iter() with None sentinel does not remove ‘Optional’ #7371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wbolster-eiq opened this issue Aug 20, 2019 · 2 comments
Closed

two-arg iter() with None sentinel does not remove ‘Optional’ #7371

wbolster-eiq opened this issue Aug 20, 2019 · 2 comments

Comments

@wbolster-eiq
Copy link

The 2-arg form of iter() takes a callable and a sentinel value. Quoting its docstring:

iter(callable, sentinel) -> iterator

[...], the callable is called until it returns the sentinel.

When the sentinel is the literal None, this means that a callable that returns an Optional[T] is transformed into a Iterator[T]. However, mypy does not detect that, and reveal_type on the iter() result claims its Revealed type is 'typing.Iterator[Union[T, None]]', which allows for None values, which is impossible.

Here's a small example:

from typing import Optional

def maybe_int() -> Optional[int]:
    return 123  # or maybe None

for n in iter(maybe_int, None):
    print(n + n)

Even though n is always an int inside the loop (never None), mypy (version 0.720) is not aware of that, and complains:

error: Unsupported operand types for + ("int" and "None")
error: Unsupported operand types for + ("None" and "int")
error: Unsupported left operand type for + ("None")
Both left and right operands are unions

Since the code is perfectly safe, mypy should not infer that n is of type int (not Optional[int]) and should not report any errors about adding int and None values.

@ilevkivskyi
Copy link
Member

This is a typeshed issue, please report there.

@wbolster-eiq
Copy link
Author

thanks, done: python/typeshed#3201

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
0