I am trying to understand the type hint Getter[T] in the following piece of code:
Simplified example
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:
Help much appreciated since I have been breaking my head over this.
Original source code
The original source code is from the 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:
A Callable followed by a type variable means that the callable is a generic function that takes one or more arguments of generic type
T.The type variable
Tis a parameter for any generic type.The line:
defines
Getteras a type alias for a callable function whose arguments are of generic typeTand string, and whose return type is string.Therefore, the line:
defines an argument (
get_from_carrier) that is a generic function. And the first argument of the generic function is of generic typeT.Concrete Example
This can be better understood by looking at a concrete example. See
propagators.extractbelow from "instrumentation/opentelemetry-instrumentation-asgi/src/opentelemetry/instrumentation/asgi/init.py ":In the call
propagators.extract, the functionget_header_from_scopeis a callable function whose first argument is of typedict, and thisdictis serving as aTextMapPropagatorT.