Skip to content

Conversation

@camillol
Copy link
Contributor

@camillol camillol commented Jan 2, 2025

Description

The attributes argument is currently specifies as a Dict[str, types.AttributeValue], which is invariant in its value type. As a result, you cannot pass a dictionary with a narrower value type, e.g. a dict[str, str]. But that should be allowed, since set_attributes simply adds all key-value pairs in its argument, and all such pairs are valid. Using Mapping takes care of this issue, since it's covariant in its value type.

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)

How Has This Been Tested?

  • Basic repro:
from opentelemetry import trace

span = trace.get_current_span()
attrs = {
    "key": "value",
}
span.set_attributes(attrs)

Check this with pyright. Without this change, you get an error like:

error: Argument of type "dict[str, str]" cannot be assigned to parameter "attributes" of type "Dict[str, AttributeValue]" in function "set_attributes"
  "dict[str, str]" is not assignable to "Dict[str, AttributeValue]"
    Type parameter "_VT@dict" is invariant, but "str" is not the same as "AttributeValue"
    Consider switching from "dict" to "Mapping" which is covariant in the value type (reportArgumentType)

With this change, it passes.

Does This PR Require a Contrib Repo Change?

  • Yes. - Link to PR:
  • No.

Checklist:

  • Followed the style guidelines of this project
  • Changelogs have been updated
  • Unit tests have been added
  • Documentation has been updated

This currently specifies a Dict[str, types.AttributeValue], which is invariant in its value type. As a result, you cannot pass a dictionary with a narrower value type, e.g. a dict[str, str]. But this should be allowed, since set_attributes simply adds all key-value pairs in its argument, and all such pairs are valied. Using Mapping takes care of this issue, since it's covariant in its value type.
@camillol camillol requested a review from a team as a code owner January 2, 2025 06:11
@xrmx xrmx added the Skip Changelog PRs that do not require a CHANGELOG.md entry label Jan 14, 2025
@lzchen lzchen merged commit 59b225f into open-telemetry:main Jan 15, 2025
381 checks passed
xrmx pushed a commit to xrmx/opentelemetry-python that referenced this pull request Jan 20, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Skip Changelog PRs that do not require a CHANGELOG.md entry

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants