How to type hint dictionaries that may have different custom keys and/or values?

In the previous versions of our app, people would just pass some arguments with plain strings to certain functions, as we did not have specific type hinting or data types for some of them. Something like:

# Hidden function signature:
def dummy(var: str):
    pass

# Users:
dummy("cat")

But now we want to implement custom data types for those function signatures, while providing backward compatibility. Say something like this:

# Signature:
def dummy(var: Union[NewDataType, Literal["cat"]])

# Backward compatibility:
dummy("cat")

# New feature:
dummy(NewDataType.cat)

Achieving this for simple function signatures is fine, but the problem comes when the signatures are more complex.

How to implement this if the argument of dummy is a dictionary that can take both Literal["cat"] and NewDataType as keys? Furthermore, how to achieve this if the argument is a dictionary with the same previous key type combination, but that could also have str and int as values (and the four possible combinations)? All of this must be compliant with mypy, pylint and use Python 3.9 (no StrEnum or TypeAlias).

I have tried many different combinations like the following:

from typing import TypedDict, Literal, Dict, Union
from enum import Enum

# For old support:
AnimalsLiteral = Literal[
    "cat",
    "dog",
    "snake",
]

# New datatypes:
class Animals(Enum):
    cat = "cat"
    dog = "dog"
    snake = "snake"

# Union of Animals Enum and Literal types for full support:
DataType = Union[Animals, AnimalsLiteral]

# option 1, which fails:
def dummy(a: Dict[DataType, str]):
    pass

# option 2, which also fails:
# def dummy(a: Union[Dict[DataType, str], Dict[Animals, str], Dict[AnimalsLiteral, str]]):
#    pass

if __name__ == "__main__":
    # Dictionary with keys as Animals Enum
    input_data1 = {
        Animals.dog: "dog",
    }
    dummy(input_data1)

    # Dictionary with keys as Literal["cat", "dog", "snake"]
    input_data2 = {
        "dog": "dog",
    }
    dummy(input_data2)

    # Dictionary with mixed keys: Animals Enum and Literal string
    input_data3 = {
        Animals.dog: "dog",
        "dog": "dog",
    }
    dummy(input_data3)

dummy(input_data1) is fine, but dummy(input_data2) gives the following mypy errors with signature 2 for dummy:

Argument 1 to "dummy" has incompatible type "dict[str, str]"; expected "Union[dict[Union[Animals, Literal['cat', 'dog', 'snake']], str], dict[Animals, str], dict[Literal['cat', 'dog', 'snake'], str]]"Mypyarg-type
Argument 1 to "dummy" has incompatible type "dict[str, str]"; expected "Union[dict[Union[Animals, Literal['cat', 'dog', 'snake']], str], dict[Animals, str], dict[Literal['cat', 'dog', 'snake'], str]]"Mypyarg-type
(variable) input_data2: dict[str, str]

Of course doing something like:

input_data2: DataTypes = {
    "dog": "dog",
}

would solve it, but I can’t ask the users to always do that when they create their datatypes.

Also, I have tried another alternative using TypedDict, but I still run into the same type of mypy errors.

In the end, I want to be able to create mypy and pylint compliant typehints of dictionaries which may take custom key types (as in the example) and even custom value types, or combination of the above.

New contributor

Figue is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật