[Python] Type hint empty dict

Discussão em 'Python' iniciado por Stack, Setembro 15, 2025.

  1. Stack

    Stack Membro Participativo

    I need to type-hint that a value is either some TypedDict or a completely empty dict. The TypedDict itself already exists and is non-trivial, and it's an all-or-nothing situation – so modifying the TypedDict to have optional keys is not sufficient.

    How can I type-hint the "completely empty dict" part for use in a union or similar?

    Since I already use TypedDict, defining an empty TypedDict seems natural. However, neither MyPy nor PyRight meaningfully accept this: the resulting type cannot actually be used even as a trivial Mapping.

    from typing import TypedDict, Mapping

    class EmptyDict(TypedDict): pass
    def foo(bar: Mapping[str, float]) -> None:...

    foo(EmptyDict())


    MyPy rejects this with:


    error: Argument 1 to "foo" has incompatible type "EmptyDict"; expected "Mapping[str, float]" [arg-type]​

    PyRight rejects this with:


    Argument of type "EmptyDict" cannot be assigned to parameter "bar" of type "Mapping[str, float]" in function "foo"
    "EmptyDict" is not assignable to "Mapping[str, float]"
    Type parameter "_VT_co@Mapping" is covariant, but "object" is not a subtype of "float"
    "object" is not assignable to "float" (reportArgumentType)​

    Continue reading...

Compartilhe esta Página