Use a covariant type for detectors argument (#5135)
This updates the type annotation for `get_aggregated_resources`'s
`detectors` argument to use `collections.abc.Sequence`, which is
covariant in its type parameter and thus has the expected behaviour for
an input type.
`typing.List` is invariant in its type parameter, which means that a
simple list of `ResourceDetector` subclasses is not a
`list[ResourceDetector]`.
Some typecheckers are more lenient than others, but [ty] enforces this
and thus the following code does not typecheck despite being
semantically correct.
from opentelemetry.sdk.resources import (
OsResourceDetector,
ProcessResourceDetector,
Resource,
get_aggregated_resources,
)
from opentelemetry.sdk.trace import TracerProvider
resource = Resource.create()
resource_detectors = [
ProcessResourceDetector(),
OsResourceDetector(),
]
tracer_provider = TracerProvider(
resource=get_aggregated_resources(
detectors=resource_detectors,
initial_resource=resource,
),
)
The full output of ty is as follows:
$ uv run ty check
error[invalid-argument-type]: Argument to function `get_aggregated_resources` is incorrect
--> test.py:18:9
|
18 | detectors=resource_detectors,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Expected `list[ResourceDetector]`, found `list[ProcessResourceDetector | OsResourceDetector]`
|
info: Function defined here
--> .venv/lib/python3.13/site-packages/opentelemetry/sdk/resources/__init__.py:507:5
|
507 | def get_aggregated_resources(
| ^^^^^^^^^^^^^^^^^^^^^^^^
508 | detectors: typing.List["ResourceDetector"],
| ------------------------------------------ Parameter declared here
|
info: `list` is invariant in its type parameter
info: Consider using the covariant supertype `collections.abc.Sequence`
info: For more information, see https://docs.astral.sh/ty/reference/typing-faq/#invariant-generics
Found 1 diagnostic
[ty]: https://docs.astral.sh/ty/reference/typing-faq/#invariant-generics
Co-authored-by: Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com> N
Nick Stenning committed
0844b5e5f36d81daf63c5df3171e3b1a68b28b71
Parent: 3b235fe
Committed by GitHub <noreply@github.com>
on 4/30/2026, 1:41:46 PM