71

I was asked recently what this means in Python:

>>> char : str

I had no idea. I checked the docs and there isn't anything like that. One suggestion was that it is static type declaration, but there is absolutely nothing in the docs about that either.

With the above, if I >>> type(char) it fails

If I >>> char : str = 'abc' it works, and the results of type(char) is <class: str>. It can't be static declaration though, because I can >>> char : str = 4 and type(char) becomes <class: int>.

What does that mean?

Zoe
  • 27,060
  • 21
  • 118
  • 148
addohm
  • 2,248
  • 3
  • 14
  • 40

1 Answers1

73

You are looking at an annotation for a variable. The hint is moved to the __annotations__ mapping:

>>> char: str
>>> __annotations__
{'char': <class 'str'>}

Variable annotations are there to support third-party tooling, such as type checkers; the syntax is new in Python 3.6.

See PEP 526 -- Syntax for Variable Annotations, and What's new in Python 3.6:

Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 2
    Thanks! Looks like it started in 3.5. >.< Guess I missed this one. https://docs.python.org/3/whatsnew/3.5.html?highlight=hint#whatsnew-pep-484 – addohm Aug 01 '18 at 17:48
  • 3
    @Jaberwocky: 3.5 added type hinting, but the *variable annotation* syntax you used is specific to Python 3.6. (don't get confused with annotations in function definitions, those have been part of Python 3 since version 3.0). – Martijn Pieters Aug 01 '18 at 17:50
  • it's typing hints in Python, For more information, please refer to: https://docs.python.org/3.7/library/typing.html?highlight=typing#module-typing – libin May 07 '20 at 09:13
  • 5
    @BinLee: no, it's *annotations*. Type hints build on top of Python's annotations model, and it was certainly an important driver of extending annotations to variables, but it is not the same thing. You are free to use the same syntax for other purposes. – Martijn Pieters May 07 '20 at 10:54