复杂的 Python 类型设置

huangapple go评论85阅读模式
英文:

Complex typing in Python

问题

def settings_traversal(
    settings: list[Union["ComponentSetting", "CompositeComponentSetting"]],
    query_params: list[str],
) -> list[Union[str, bool, Type["BaseCountryRatingComponent"]]]:
    pass

def get_model_and_orm_key(
    self,
) -> list[tuple[Type["BaseCountryRatingComponent"], str]]:
    return settings_traversal(settings, ["model", "orm_key"])
英文:

I can't figure out how to properly define return types for the function.

Details:

This is the function that parses the settings object and returns a list of parameter values, it can be tuple[str], tuple[str, str], tuple[Type[BaseCountryRatingComponent], bool] whatever from the set of [str, bool, Type[BaseCountryRatingComponent]].

Question:

How to properly define return types for settings_traversal?

from typing import Union, Type

class BaseCountryRatingComponent:
    pass

class ComponentSetting:
    pass

class CompositeComponentSetting:
    pass

def settings_traversal(
    settings: list[Union["ComponentSetting", "CompositeComponentSetting"]],
    query_params: list[str],
) -> list[Union[str, bool, Type["BaseCountryRatingComponent"]]]:
    pass

def get_model_and_orm_key(
    self,
) -> list[tuple[Type["BaseCountryRatingComponent"], str]]:
    return settings_traversal(settings, ["model", "orm_key"])

答案1

得分: 0

以下是翻译好的部分:

一种可能的方法是手动编写我们需要的一切

@classmethod
    def settings_traversal(
        cls,
        settings: list[Union[ComponentSetting, CompositeComponentSetting]],
        query_params: list[str],
    ) -> list[
        Union[
            str,
            tuple[Type[BaseCountryRatingComponent], str],
            tuple[str, str],
            tuple[str, str, bool],
            tuple[Union[str, bool, Type[BaseCountryRatingComponent]], ...],
        ]
    ]:

或者简化返回类型为

@classmethod
def settings_traversal(
    cls,
    settings: list[Union[ComponentSetting, CompositeComponentSetting]],
    query_params: list[str],
) -> list[Any]
英文:

One possible way is to manually write everything we need

@classmethod
    def settings_traversal(
        cls,
        settings: list[Union[ComponentSetting, CompositeComponentSetting]],
        query_params: list[str],
    ) -> list[
        Union[
            str,
            tuple[Type[BaseCountryRatingComponent], str],
            tuple[str, str],
            tuple[str, str, bool],
            tuple[Union[str, bool, Type[BaseCountryRatingComponent]], ...],
        ]
    ]:

or simplifies the return types to the

@classmethod
def settings_traversal(
    cls,
    settings: list[Union[ComponentSetting, CompositeComponentSetting]],
    query_params: list[str],
) -> list[Any]

huangapple
  • 本文由 发表于 2023年2月19日 20:16:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定