Python多重返回类型提示最佳实践



下面的方法有许多基于字典中值的潜在返回类型;

def get_config(self, key: str | None = None) -> int | dict | str | list | bool | None:
return self._config[key] if key else self._config

我在配置文件中可用的类型仅限于上面指定的类型,但在什么情况下特定于列表的类型是多余的?我应该在这里设置Any吗?

如果要返回数据类型(如intstr(而不返回实例(如863"hello world"(,则返回类型的类型提示应为type

class Klaus:
def get_config(self, key: str | None = None) -> type:
return self._config[key] if key else self._config

好的,所以经过一点阅读,我发现了我认为最好的处理方法:

将get_config方法更改为以下;

def __init__(self) -> None:
self._service: LocalService = LocalService()
self._config: ConfigModel = self._service.load_json(PATH, DEFAULT_CONFIG)
def get_config(self) -> ConfigModel:
return self._config

然后我用打字。TypedDict为我的配置文件的整个结构添加类型提示;

from typing import TypedDict
class CategoryModel(TypedDict, total=False):
# All
enabled: bool
prefix: str | None
# Generics
allowed_ids: list[str]
method: str
enable_prefix: bool
suffix: str | None
# Ratings
absolute_buckets: list[int]
min_votes_required: int
not_enough_votes_treatment: str
relative_count: int
weight_ratings_by_votes: bool
class CategorisationSettingsModel(TypedDict):
perspectives: CategoryModel
ratings: CategoryModel
release_date: CategoryModel
themes: CategoryModel
class SearchSettingsModel(TypedDict):
fallback_to_name_search: bool
filter_words: list[str]
refresh_cache_days: int
class PlatformParsingSettingsModel(TypedDict):
enabled: bool
prefix: str | None
platform_map: dict[str, list[int]] | None
class ConfigModel(TypedDict):
api_auth: dict[str, str]
categorisation_settings: CategorisationSettingsModel
search_settings: SearchSettingsModel
platform_parsing: PlatformParsingSettingsModel
overrides: dict[str, str]

最新更新