<code>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'])
</code>
<code>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'])
</code>
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
<code>pip install mypy
</code>
<code>pip install mypy
</code>
pip install mypy
then run
<code> mypy filename.py
</code>
<code> mypy filename.py
</code>
mypy filename.py
then you’ll start seeing the errors like this
<code>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)
</code>
<code>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)
</code>
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)