python中关于类型作为参数的复杂注释

2024-10-02 22:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个玩具实例,考虑一个函数,该函数采用两种类型^ {CD1>},^ {CD2>},并返回对象{^ }。这方面的标准示例是A = defaultdictB,例如int。我怎样才能注释这样的东西?最接近的是

from collections import defaultdict
from typing import TypeVar, Type, Protocol

Val = TypeVar('Val')


class InitableMapping(Protocol[Val]):
    """
    A Protocol that enforces a MutableMapping with a special __init__
    """
    def __init__(self, value_type: Type[Val]):
        ...

    def __getitem__(self, item: int) -> Val:
        ...

    def __setitem__(self, key: int, value: Val) -> None:
        ...

    # more methods


M = TypeVar('M', bound=InitableMapping)


def build_mapping(mapping_type: Type[M], value_type: Type[Val]) -> InitableMapping[Val]:
    return mapping_type(value_type)


foo = build_mapping(defaultdict, int)
print(foo.default_factory)  # "InitableMapping[int]" has no attribute "default_factory"

我将MyPy输出放在注释中

显然,返回注释InitableMapping[Val]太宽了,但是M[int, Val]无法工作

我很高兴能在这方面得到任何帮助:)事实上,即使是一些关于寻找什么的关键词也会很好-我很难想出一个描述性的问题标题


更新:一个更现实的例子可能是

class MyClass(Generic[M, Val]):
    def __init__(self, load: Callable[[], M[int, Val]]) -> None:
        self.data = load()

Tags: 函数fromselfinitvaluedeftypeval