Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can mypy infer the type of containers such as collections Counter

Running this mypy gist (https://mypy-play.net/?mypy=latest&python=3.12&gist=58a8148f2c95c7a282a6f8a11ccd689a)

from collections import Counter

C = Counter()

gives this mypy error:

main.py:3: error: Need type annotation for "C"  [var-annotated]
Found 1 error in 1 file (checked 1 source file)

Is there any way that mypy could infer this type?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Mypy does infer it if you initialize the Counter with some data, but if you don’t want to pass anything in the initializer, you must give a type annotation to C, where you specify the generic type e.g., C: Counter[str].

See this section in the mypy docs: Types of empty collections

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading