How to type hint a dictionary with values of different types

You are looking for TypedDict. It is currently only a mypy-only extension, but there are plans to make it an officially sanctioned type in the near-future. I am not sure if PyCharm supports this feature yet, though.

So, in your case, you’d do:

from mypy_extensions import TypedDict

RectangleElements = TypedDict('RectangleElements', {
    'front': Line,
    'left': Line,
    'right': Line,
    'rear': Line,
    'cog': float,
    'area': float,
    'pins': Optional[List[Pin]]
})

class Rectangle:
    def __init__(self, corners: Tuple[Tuple[float, float]], **kwargs):
        self.x, self.z = corners[0][0], corners[0][1]
        self.elements = {
            'front': Line(corners[0], corners[1]),
            'left': Line(corners[0], corners[2]),
            'right': Line(corners[1], corners[3]),
            'rear': Line(corners[3], corners[2]),
            'cog': calc_cog(corners),
            'area': calc_area(corners),
            'pins': None
        }  # type: RectangleElements

If you are using Python 3.6+, you can type this all more elegantly using the class-based syntax.

In your specific case though, I think most people would just store those pieces of data as regular fields instead of a dict. I’m sure you’ve already thought through the pros and cons of that approach though, so I’ll skip lecturing you about it.

Leave a Comment