Код: Выделить всё
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
Код: Выделить всё
def equivalent_to_dictionary(po: PossibleOption) -> str:
match po:
case Option1():
return "aa"
case Option2():
return "bb"
case Option3():
return "cc"
Но я хочу, чтобы пользователю было проще...
Есть ли способ статически проверить с помощью mypy, что каждый параметр (Option1, Option2, Option3 в данном конкретном случае) присутствует в качестве ключа в словаре?
Подробнее здесь: https://stackoverflow.com/questions/792 ... options-in