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

Use of colon ':' in type hints

When type annotating a variable of type dict, typically you’d annotate it like this:

numeralToInteger: dict[str, int] = {...}

However I rewrote this using a colon instead of a comma:

numeralToInteger: dict[str : int] = {...}

And this also works, no SyntaxError or NameError is raised.

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

Upon inspecting the __annotations__ global variable:

colon: dict[str : int] = {...}
comma: dict[str, int] = {...}

print(__annotations__)

The output is:

{'colon': dict[slice(<class 'str'>, <class 'int'>, None)],
 'comma': dict[str, int]}

So the colon gets treated as a slice object and the comma as a normal type hint.

Should I use the colon with dict types or should I stick with using a comma?

I am using Python version 3.10.1.

>Solution :

If you have a dictionary which it’s keys are strings and it’s values are integers, you should do dict[str, int]. It’s not optional. IDEs and type-checkers use these type hints to help you. When you say dict[str : int] is a slice object. Totally different things.

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