Update force_bytes and force_unicode to support casting objects to strings.
Review Request #13033 — Created May 10, 2023 and submitted
force_bytes()
andforce_unicode()
now take astrings_only
boolean
argument, which defaults toTrue
for backwards-compatibility. When set
toFalse
, these functions can take any arbitrary object and try to
turn it into a string.
force_bytes()
will look for a__bytes__()
dunder method, using that to
get the result, and then falling back on__str__()
.
force_unicode()
will just look for__str__()
. Since every object has
this, it will technically work with any object.Typing has been updated to provide overloads based on the
strings_only
parameter, helping to ensure callers receive type warnings if they
provide something other than a string without opting into
strings_only=False
.Unit tests have been added to cover this module.
Unit tests pass.
Tested this with some upcoming fixes for command output rendering.