Search code examples
pythonslicepython-typing

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.

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 whose keys are strings and 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], it is a slice object. Totally different things.

    Try these in mypy playground:

    d: dict[str, int]
    d = {'hi': 20}
    
    c: dict[str: int]
    c = {'hi': 20}
    

    message:

    main.py:4: error: "dict" expects 2 type arguments, but 1 given
    main.py:4: error: Invalid type comment or annotation
    main.py:4: note: did you mean to use ',' instead of ':' ?
    Found 2 errors in 1 file (checked 1 source file)
    

    Error messages are telling everything