0

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.

1 Answer 1

1

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$
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.