[Python] How to statically check with mypy that a dictionary has keys for all options in a...

Discussão em 'Python' iniciado por Stack, Novembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I have a Union type PossibleOption composed of n dataclasses, and I want to create a dictionary where the keys are instances of these classes. I need to statically check with mypy that the dictionary includes a key for each option in the Union. Here's my current code:

    from dataclasses import dataclass
    from typing import Union

    @dataclass
    class Option1:
    def __hash__(self): #don t focus too much on this method, A dictionary need a hashable key. that s all
    return hash(type(self))

    @dataclass
    class Option2:
    def __hash__(self):
    return hash(type(self))

    @dataclass
    class Option3:
    def __hash__(self):
    return hash(type(self))

    PossibleOption = Union[Option1, Option2, Option3]

    # I want to create a dictionary like this:
    a = {Option1(): "a",Option2(): "bb",Option3(): "cc"}
    # print(a[Option2()]) prints "bb" for example


    I know that I could ask the user to give a function taking PossibleOption as paratmer and returning the the value like that:

    def equivalent_to_dictionary(po: PossibleOption) -> str:
    match po:
    case Option1():
    return "aa"
    case Option2():
    return "bb"
    case Option3():
    return "cc"


    and mypy can check is each option are covered But I want to keep things simple for the user...

    Is there a way to statically check with mypy that each option (Option1, Option2, Option3 in this particular case) is present as a key in the dictionary?

    Continue reading...

Compartilhe esta Página