from typing_extensions import TypedDict
class Person(TypedDict):
name: str
age: int
is_employee: bool
person: Person = {
"name": "Baber",
"age": "ten year", #as i assagin "string" datatype to age instead of "int" but it does not show any error?
"is_employee": True
}
print(person['age'])
I want this function to show me error due to wrong assignment to integer variable.
4
if you want to catch type errors like assigning a string to an integer field, you need to use a type checker like mypy
because python won’t raise type errors at runtime based on type hints. You need tools like mypy
for static type checking.
first install mypy
pip install mypy
then run
mypy filename.py
then you’ll start seeing the errors like this
filename.py:8: error: Incompatible types (expression has type "str", TypedDict item "age" has type "int")
Found 1 error in 1 file (checked 1 source file)