python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.27k stars 2.79k forks source link

Prime number sieve with generators example does not pass mypy #17414

Closed chrisirhc closed 3 months ago

chrisirhc commented 3 months ago

Bug Report

The Prime number sieve with generators Mypy with static typing example does not pass on mypy. It's also not clear what needs to be done to make the example work. Typing numbers seems to work.

To Reproduce

# Taken directly from https://mypy-lang.org/examples.html
import itertools
from typing import Iterator

def iter_primes() -> Iterator[int]:
     # An iterator of all numbers between 2 and
     # +infinity
     numbers = itertools.count(2)

     # Generate primes forever
     while True:
         # Get the first number from the iterator
         # (always a prime)
         prime = next(numbers)
         yield prime

         # This code iteratively builds up a chain
         # of filters...
         numbers = filter(prime.__rmod__, numbers)

for p in iter_primes():
    if p > 1000:
        break
    print(p)

https://mypy-play.net/?mypy=master&python=3.9&gist=52970ddb2c5cd827dafa8f8af5219f89

Expected Behavior

No errors.

Actual Behavior

main.py:18: error: Incompatible types in assignment (expression has type "filter[int]", variable has type "count[int]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

Your Environment

Suggested fix I guess changing numbers = itertools.count(2) to numbers: Iterator[int] = itertools.count(2) seems to work. Perhaps we should update the mypy example?

hauntsaninja commented 3 months ago

Yeah, this was broken by a typeshed change a few years ago https://github.com/python/typeshed/issues/5145 In general, mypy-lang.org could use some love. I believe https://github.com/JukkaL/mypy-website is the repo for the website

chrisirhc commented 3 months ago

Ah got it. Thanks! 👍 Opened https://github.com/JukkaL/mypy-website/pull/27