Код: Выделить всё
from enum import Enum
from dataclasses import make_dataclass, field, dataclass
class DatasetNames(Enum):
test1 = "test1_string"
test2 = "test2_string"
test3 = "test3_string"
def get_path(s: str) -> str:
return s + "_path"
# the normal way to do this, but I have to type every new dataset name twice
# and there's a lot of duplicate code
@dataclass(frozen=True)
class StaticDatasetPaths:
test1 = get_path("test1_string")
test2 = get_path("test2_string")
test3 = get_path("test3_string")
# mypy recognizes that `StaticDatasetPaths` is a class
# mypy recognizes that `StaticDatasetPaths.test2` is a string
print(StaticDatasetPaths.test2) # 'test2_string_path'
# this is my way of doing it, without having to type every new dataset name twice and no duplicate code
DynamicDatasetPaths = make_dataclass(
'DynamicDatasetPaths',
[
(
name.name,
str,
field(default=get_path(name.value))
)
for name in DatasetNames
],
frozen=True
)
# mypy thinks `DynamicDatasetPaths` is a `variable` of type `type`
# mypy thinks that `DynamicDatasetPaths.test2` is an `function` of type `Unknown`
print(DynamicDatasetPaths.test2) # 'test2_string_path'
Обычно при запуске в подобных случаях я могу просто использовать приведение и сообщить mypy, какой тип правильный, но я не знаю правильного типа для «замороженного класса данных, атрибутами которого являются строки».
(Кроме того, если есть лучший способ избежать дублирования кода, я тоже буду рад об этом услышать.)
Подробнее здесь: https://stackoverflow.com/questions/790 ... -dataclass