Reputation: 133
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?
Upvotes: 3
Views: 219
Reputation: 95722
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.
Upvotes: 5