| 1 |
# Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]> |
| 2 |
# MIT License (see LICENSE or https://opensource.org/licenses/MIT) |
| 3 |
|
| 4 |
import typing |
| 5 |
|
| 6 |
|
| 7 |
def _obj_str( |
| 8 |
obj: typing.Any, |
| 9 |
default: str, |
| 10 |
) -> str: |
| 11 |
# First try to get the str() then repr() before falling back to the default value. |
| 12 |
to_str_funcs: typing.List[typing.Callable] = [str, repr] |
| 13 |
for func in to_str_funcs: |
| 14 |
try: |
| 15 |
obj = func(obj) |
| 16 |
except (UnicodeError, TypeError): |
| 17 |
continue |
| 18 |
else: |
| 19 |
return obj |
| 20 |
else: |
| 21 |
return default |
| 22 |
|
| 23 |
|
| 24 |
def to_bytes( |
| 25 |
obj: typing.Any, |
| 26 |
encoding: str = "utf-8", |
| 27 |
errors: str = "strict", |
| 28 |
nonstring: str = "str", |
| 29 |
) -> typing.Any: |
| 30 |
if isinstance(obj, bytes): |
| 31 |
return obj |
| 32 |
elif isinstance(obj, str): |
| 33 |
return obj.encode(encoding, errors) |
| 34 |
|
| 35 |
if nonstring == "str": |
| 36 |
return to_bytes(_obj_str(obj, ""), encoding=encoding, errors=errors) |
| 37 |
elif nonstring == "passthru": |
| 38 |
return obj |
| 39 |
elif nonstring == "empty": |
| 40 |
return b"" |
| 41 |
else: |
| 42 |
raise ValueError("Invalid nonstring value '%s', expecting str, passthru, or empty" % nonstring) |
| 43 |
|
| 44 |
|
| 45 |
def to_text( |
| 46 |
obj: typing.Any, |
| 47 |
encoding: str = "utf-8", |
| 48 |
errors: str = "strict", |
| 49 |
nonstring: str = "str", |
| 50 |
) -> typing.Any: |
| 51 |
if isinstance(obj, str): |
| 52 |
return obj |
| 53 |
elif isinstance(obj, bytes): |
| 54 |
return obj.decode(encoding, errors) |
| 55 |
|
| 56 |
if nonstring == "str": |
| 57 |
try: |
| 58 |
obj = obj.__unicode__() |
| 59 |
except (AttributeError, UnicodeError): |
| 60 |
obj = _obj_str(obj, "") |
| 61 |
|
| 62 |
return to_text(obj, errors=errors, encoding=encoding) |
| 63 |
elif nonstring == "passthru": |
| 64 |
return obj |
| 65 |
elif nonstring == "empty": |
| 66 |
return "" |
| 67 |
else: |
| 68 |
raise ValueError("Invalid nonstring value '%s', expecting repr, passthru, or empty" % nonstring) |