opentelemetry-python: ReadableSpan.attributes Type Hint Fix

I looked at the last week of opentelemetry-python, the Python SDK and API for OpenTelemetry tracing. It was a quiet week. One change landed, but it is the kind of small fix that saves downstream authors real time: the type hint on ReadableSpan.attributes now says what the property actually returns.

The ReadableSpan.attributes type hint

The SDK exposes span data for exporters and processors through the ReadableSpan class. Its attributes property always returns a mapping. The implementation wraps the internal dict with MappingProxyType and falls back to an empty mapping, so a None return is impossible. The old hint said the property returned types.Attributes, which is an alias that type checkers may treat as optional in the API layer. Anyone calling .attributes on a span and then indexing it got a warning from mypy or pyright, even though the code was safe.

Pull request #5956 fixes the hint. The change is in opentelemetry-sdk/src/opentelemetry/sdk/trace/init.py, and the commit is a one line type correction:

@property
def attributes(self) -> Mapping[str, types.AnyValue]:
    return MappingProxyType(self._attributes or {})

Two things are now explicit. First, the return value is never None. Second, you get a read only Mapping, not a mutable dict. That second point matters if you are writing an exporter: the proxy prevents accidental writes into span state, and the hint now documents it.

Tests and changelog

The fix comes with a test added to opentelemetry-sdk/tests/trace/test_trace.py. The new test_attributes covers both cases:

  • a span built with no attributes returns an empty mapping
  • a span built with attributes returns them unchanged
span = trace.ReadableSpan("test")
self.assertEqual(span.attributes, {})

The changelog entry lives in .changelog/5956.fixed and reads as a fix to the SDK, correct for a user visible signature change. Expect it in the next opentelemetry-sdk release notes.

What to watch

  • If your code did span.attributes or {} as a None guard, that guard is now unnecessary. Removing it is optional, but the checkers may flag unreachable branches.
  • Type checking tools will start reporting differently against the next SDK release. If you pin the SDK, verify your exporter or processor code still passes mypy or pyright after you upgrade.
  • The window had exactly one commit, so there is nothing else to track this week. Small weeks happen in mature projects, and a one line fix with a test and a changelog entry is a normal maintenance cadence.

Where to read more: the opentelemetry-python repository on GitHub.

← All updates