Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

python 3.x - What does the colon (:) do in this code do?

I accidentally used : instead of = when assigning a variable, and I was surprised that it didn't generate an error. For example, the following runs without complaints:

Python 3.7.4 (default, Jul  9 2019, 18:15:00)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a: 'hello world'
>>>

However, this doesn't seem to actually do anything. I've tried looking in the documentation and tutorials, I only find compound statements, dict comprehensions and sequence slicing, and I can't see how either of those apply in this case.

For comparison, in Python 2.7 it does generate a syntax error:

Python 2.7.16 (default, Apr 12 2019, 15:32:52)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a: 'hello world'
  File "<stdin>", line 1
    a: 'hello world'
     ^
SyntaxError: invalid syntax

Why does this not cause a syntax error in Python 3.7, and what (if anything) could it be used for?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Recent versions of Python support a syntax known as type hinting, or type annotations. This syntax lets you write a: int to declare that in the current context the variable a will have the type int.

The compiler doesn't actually check that and in fact will allow any expression after the variable name so the string you used will be accepted as a valid type hint.

See https://www.python.org/dev/peps/pep-0526/ for a detailed description of type hints.

If you do add type hints to your code then you can use a tool such as mypy so perform static type checking.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...