Skip to content

chore: tidy to_unicode() in compat.py #13740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 1 addition & 12 deletions ddtrace/internal/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,23 +46,12 @@ def is_integer(obj: Any) -> bool:
return isinstance(obj, int) and not isinstance(obj, bool)


# DEV: There is `six.u()` which does something similar, but doesn't have the guard around `hasattr(s, 'decode')`
def to_unicode(s: AnyStr) -> Text:
def to_unicode(s: Union[str, bytes, bytearray]) -> str:
"""Return a unicode string for the given bytes or string instance."""
# No reason to decode if we already have the unicode compatible object we expect
# DEV: `six.text_type` will be a `str` for python 3 and `unicode` for python 2
# DEV: Double decoding a `unicode` can cause a `UnicodeEncodeError`
# e.g. `'\xc3\xbf'.decode('utf-8').decode('utf-8')`
if isinstance(s, str):
return s

# If the object has a `decode` method, then decode into `utf-8`
# e.g. Python 2 `str`, Python 2/3 `bytearray`, etc
if hasattr(s, "decode"):
return s.decode("utf-8", errors="ignore")

# Always try to coerce the object into the `six.text_type` object we expect
# e.g. `to_unicode(1)`, `to_unicode(dict(key='value'))`
return str(s)


Expand Down
Loading