Correct way to type narrow / type assertion for a TypedDict in python

74 views Asked by At

Let's say I have the following variable:

target: EquatorialCoordinate | HorizontalCoordinate = { "ra": 88, "dec": 7 }

Where the EquatorialCoordinate and / or HorizontalCoordinate types are defined using the TypedDict type class annotation:

from typing import TypedDict


class EquatorialCoordinate(TypedDict):
    ra: float
    dec: float


class HorizontalCoordinate(TypedDict):
    alt: float
    az: float

Then, I pass this variable as:

if type(target) is EquatorialCoordinate:
    target = convert_equatorial_to_horizontal(date, observer, target)

At this point, from my perspective, the target type can only ever be HorizontalCoordinate ... but in fact this is wrong, as the type(target) is actually <class 'dict'> as Python isn't able to evaluate the types at runtime (totally expected).

Therefore, I am wondering what is the best way to correctly perform type narrowing / assertion for a TypedDict in Python?

I'm thinking it is probably best to define some assertion function:

def is_equatorial_coordinate(coordinate: dict) -> EquatorialCoordinate | None:
    return (
        EquatorialCoordinate({"ra": coordinate["ra"], "dec": coordinate["dec"]})
        if "ra" in coordinate and "dec" in coordinate
        else None
    )
0

There are 0 answers