Can you actually declare the data type for a variable in python?

I just learned that you can define what kind of value you want a variable to hold using the syntax “x: type”. But when I actually try it myself in Visual Studio Code, nothing seems to happen. For example, if I write:

x: int
x = 'number'
print(x)

it just prints the word ‘number’, and I don’t get any kind of warning about it. I’m using Python 3.9 and don’t have any other version installed.

Answer

Types in python are not tested at runtime, you need to verify them via something like http://mypy-lang.org “at compile time”, like this:

(venv) rasjani@MacBook-Pro ~/src/test$ cat test.py
x: int
x = 'number'
print(x)
(venv) rasjani@MacBook-Pro ~/src/test$ mypy test.py
test.py:2: error: Incompatible types in assignment (expression has type "str", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
(venv) rasjani@MacBook-Pro ~/src/test$