Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of colon in variable declaration [duplicate]

Tags:

python

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?

like image 883
addohm Avatar asked Aug 01 '18 17:08

addohm


People also ask

What does colon equals mean in programming?

Very recently, Python 3.8 introduced the use of 'colon equals' ( := ), which is similar to the equals operator ( = ). The use of this operator allows for speedup and shortened code, and it's definitely valuable to understand. This notation comes from a complaint rooted in mathematics.

What does this declaration mean in text colon for?

It means it's a bitfield - i.e. the size of dumpable is a single bit, and you can only assign 0 or 1 to it.

What does colon ':' operator do in Python?

The − operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice.

What does the colon after a variable mean C++?

In C++, the colon ':' operator, to my understanding, is used for inheritance.


1 Answers

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.

like image 165
Martijn Pieters Avatar answered Oct 17 '22 08:10

Martijn Pieters