<p>后跟类型变量的Callable表示Callable是一个泛型函数,它接受一个或多个泛型类型<code>T</code>的参数</p>
<p>类型变量<code>T</code>是任何泛型类型的参数</p>
<p>该行:</p>
<pre class="lang-py prettyprint-override"><code>Getter = Callable[[T, str], str]
</code></pre>
<p>将<code>Getter</code>定义为可调用函数的类型别名,该函数的参数为泛型类型<code>T</code>和字符串,返回类型为字符串</p>
<p>因此,该行:</p>
<pre class="lang-py prettyprint-override"><code>get_from_carrier: Getter[T]
</code></pre>
<p>定义泛型函数的参数(<code>get_from_carrier</code>)。泛型函数的第一个参数是泛型类型<code>T</code></p>
<h2>具体例子</h2>
<p>通过看一个具体的例子,可以更好地理解这一点。从<a href="https://github.com/open-telemetry/opentelemetry-python/blob/master/instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/__init__.py" rel="nofollow noreferrer">"instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/<strong>init</strong>.py "</a>看下面的<code>propagators.extract</code>:</p>
<p>在调用<code>propagators.extract</code>中,函数<code>get_header_from_scope</code>是一个可调用函数,其第一个参数的类型为<code>dict</code>,并且该<code>dict</code>充当<code>TextMapPropagatorT</code></p>
<pre class="lang-py prettyprint-override"><code>def get_header_from_scope(scope: dict, header_name: str) -> typing.List[str]:
"""Retrieve a HTTP header value from the ASGI scope.
Returns:
A list with a single string with the header value if it exists, else an empty list.
"""
headers = scope.get("headers")
return [
value.decode("utf8")
for (key, value) in headers
if key.decode("utf8") == header_name
]
...
class OpenTelemetryMiddleware:
"""The ASGI application middleware.
...
"""
...
async def __call__(self, scope, receive, send):
"""The ASGI application ... """
if scope["type"] not in ("http", "websocket"):
return await self.app(scope, receive, send)
token = context.attach(
propagators.extract(get_header_from_scope, scope)
)
</code></pre>