【发布时间】:2021-01-13 06:35:10
【问题描述】:
我正在尝试理解以下代码中的类型提示Getter[T]:
简化示例
T = TypeVar('T')
Getter = Callable[[T, str], str]
class AbstractClass(abc.ABC):
@abc.abstractmethod
def extract(
self,
get_from_carrier: Getter[T], # <---- See here
...
) -> Context:
非常感谢您的帮助,因为我一直在为此烦恼。
原始源代码
原源码来自OpenTelemetry project file "textmap.py":
import abc
import typing
from opentelemetry.context.context import Context
TextMapPropagatorT = typing.TypeVar("TextMapPropagatorT")
Setter = typing.Callable[[TextMapPropagatorT, str, str], None]
Getter = typing.Callable[[TextMapPropagatorT, str], typing.List[str]]
class TextMapPropagator(abc.ABC):
"""This class provides an interface that enables extracting and injecting
context into headers of HTTP requests.
...
"""
@abc.abstractmethod
def extract(
self,
get_from_carrier: Getter[TextMapPropagatorT],
carrier: TextMapPropagatorT,
context: typing.Optional[Context] = None,
) -> Context:
【问题讨论】:
-
对我来说,这似乎无效。您从哪里获得此代码?
-
意图,至少,似乎是你传递给
get_from_elem的第二个参数具有get的第一个参数所期望的类型。 -
@chepner 那已经和
C_单独沟通了,不是吗? -
不一定;
get_from_elem(get: C_, elem: str)不会暗示get和elem之间有任何联系。 -
不,我的意思是
get_from_elem(get: _C, elem: _T)。_C的额外下标似乎试图复制_C中已有的信息。
标签: python generics type-hinting python-typing