pythondictionarytypeddict

TypedDict from typing_extensions is not working


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.


Solution

  • As explained in this answer , "python won't raise type errors at runtime based on type hints".

    mypy could be used to statically type check your program. Note that this approach works in such a straightforward example, but could fail when types are not explicitly declared with types annotations.

    For instance, using mypy on this program would pass:

    from typing_extensions import TypedDict
    
    def return_str():
        return "test"
    
    class Person(TypedDict):
        name: str
        age: int
        is_employee: bool
        
    person: Person = {
        "name": "Baber",
        "age": return_str(),
        "is_employee": True 
    }
    
    print(person['age'])
    

    An alternative to the solution of mypy, would be to use the module pydantic:

    import pydantic
    
    def return_str():
        return "test"
    
    class Person(pydantic.BaseModel):
        name: str
        age: int
        is_employee: bool
        
    person = Person.model_validate({
        "name": "Baber",
        "age": return_str(),  # error
        "is_employee": True 
    })
    
    print(person.age)
    

    Pydantic will perform runtime checks, even when type annotations are not given, and will return an error of the form:

    return cls.pydantic_validator.validate_python( pydantic_core._pydantic_core.ValidationError: 1 validation error for Person age Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='test', input_type=str]

    Note that runtime checks have to reach the error to report it. Hence, you should respect the fail-fast principle and check data as soon as possible. This has to be used when static type checkers as mypy cannot verify the types of data retrieved from other files or APIs for instance.