Incorrect error when passing wrong attribute type on Python 3.9
Describe your environment
OS: Debian 11 Python version: Python 3.9.2 API version: 1.38.0
What happened?
Passing an invalid attribute type (in my case bson.ObjectId) into a LogRecord and into emit causes an AttributeError instead of the TypeError. https://github.com/open-telemetry/opentelemetry-python/blob/62da90eda4b1348730180ce2fa0aeae72e09c7ed/opentelemetry-api/src/opentelemetry/attributes/init.py#L185 The ifs in this method fail, execution gets to the TypeError, but Mapping does not have name on 3.9 so this throws a different error and hides the cause from the error message.
Steps to Reproduce
record = logs.LogRecord(
attributes={
"test": object(),
},
)
logger.emit(record)
or directly calling the affected method
from opentelemetry.attributes import _clean_extended_attribute_value
_clean_extended_attribute_value(object(), None)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "/venv/lib/python3.9/site-packages/opentelemetry/attributes/__init__.py", line 185, in _clean_extended_attribute_value
# f"Expected one of {[valid_type.__name__ for valid_type in _VALID_ANY_VALUE_TYPES]} or a "
# File "/venv/lib/python3.9/site-packages/opentelemetry/attributes/__init__.py", line 185, in <listcomp>
# f"Expected one of {[valid_type.__name__ for valid_type in _VALID_ANY_VALUE_TYPES]} or a "
# File "/usr/lib/python3.9/typing.py", line 694, in __getattr__
# raise AttributeError(attr)
#AttributeError: __name__
Expected Result
Correct TypeError mentioning the incorrect type.
Actual Result
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/venv/lib/python3.9/site-packages/opentelemetry/attributes/__init__.py", line 185, in _clean_extended_attribute_value
f"Expected one of {[valid_type.__name__ for valid_type in _VALID_ANY_VALUE_TYPES]} or a "
File "/venv/lib/python3.9/site-packages/opentelemetry/attributes/__init__.py", line 185, in <listcomp>
f"Expected one of {[valid_type.__name__ for valid_type in _VALID_ANY_VALUE_TYPES]} or a "
File "/usr/lib/python3.9/typing.py", line 694, in __getattr__
raise AttributeError(attr)
AttributeError: __name__
Additional context
No response
Would you like to implement a fix?
None
Tip
React with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding +1 or me too, to help us triage it. Learn more here.
Looks like I think getattr(valid_type, "__name__", getattr(valid_type, "_name", None)) should to the trick. Said that given that the next release will try to stringify the value instead of raising that exception and that this is a Python 3.9 only issue and that is EOL already, we may just wait until we drop Python 3.9 support.