Search code examples
pythonpython-3.xcustom-typetypedpython-3.10

How to check if a variables fits a custom type


I have this code:

from typing import Tuple, Dict, List

CoordinatesType = List[Dict[str, Tuple[int, int]]]

coordinates: CoordinatesType = [
    {"coord_one": (1, 2), "coord_two": (3, 5)},
    {"coord_one": (0, 1), "coord_two": (2, 5)},
]

I would like to check at runtime if my variable fits my custom type definition. I was thinking on something like:

def check_type(instance, type_definition) -> bool:
    return isinstance(instance, type_definition)

But obviously isinstance is not working. I need to check this at runtime, what would be the correct way to implement it?


Solution

  • Example:

    code:

    from typeguard import check_type
    from typing import Tuple, Dict, List
    coordinates = [
        {"coord_one": (1, 2), "coord_two": (3, 5)},
        {"coord_one": (0, 1), "coord_two": (2, 5)},
    ]
    try:
        check_type('coordinates', coordinates, List[Dict[str, Tuple[int, int]]])
        print("type is correct")
    except TypeError as e:
        print(e)
    
    coordinates = [
        {"coord_one": (1, 2), "coord_two": ("3", 5)},
        {"coord_one": (0, 1), "coord_two": (2, 5)},
    ]
    try:
        check_type('coordinates', coordinates, List[Dict[str, Tuple[int, int]]])
        print("type is correct")
    except TypeError as e:
        print(e)
    

    result:

    type is correct
    type of coordinates[0]['coord_two'][0] must be int; got str instead