in elasticapm/utils/encoding.py [0:0]
def force_text(s, encoding="utf-8", strings_only=False, errors="strict"):
"""
Similar to smart_text, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# str. This function gets called often in that setting.
#
# Adapted from Django
if isinstance(s, str):
return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, str):
if hasattr(s, "__unicode__"):
s = s.__unicode__()
else:
if isinstance(s, bytes):
s = str(s, encoding, errors)
else:
s = str(s)
else:
# Note: We use .decode() here, instead of str(s, encoding,
# errors), so that if s is a SafeBytes, it ends up being a
# SafeText at the end.
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
raise UnicodeDecodeError(*e.args)
else:
# If we get to here, the caller has passed in an Exception
# subclass populated with non-ASCII bytestring data without a
# working unicode method. Try to handle this without raising a
# further exception by individually forcing the exception args
# to unicode.
s = " ".join([force_text(arg, encoding, strings_only, errors) for arg in s])
return s