Use of colon in variable declaration

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaddohmView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow