Added more explcit typing to from_unicode and changed to have one return

pull/581/head
bcapuano 2023-11-05 12:48:12 -05:00
rodzic db54100d42
commit c76012262b
1 zmienionych plików z 5 dodań i 3 usunięć

Wyświetl plik

@ -1,8 +1,10 @@
from typing import Any
SEQUENCE_TYPES = (list, tuple) SEQUENCE_TYPES = (list, tuple)
DEFAULT_ENCODING = 'utf-8' DEFAULT_ENCODING = 'utf-8'
def from_unicode(value, encoding='utf-8') -> bytes: def from_unicode(value: Any, encoding='utf-8') -> bytes:
""" """
Converts a value to bytes, even if it already is bytes Converts a value to bytes, even if it already is bytes
:param value: The value to convert :param value: The value to convert
@ -10,10 +12,10 @@ def from_unicode(value, encoding='utf-8') -> bytes:
:return: The bytes representation of the value :return: The bytes representation of the value
""" """
if isinstance(value, bytes): if isinstance(value, bytes):
return value value = value
elif isinstance(value, str): elif isinstance(value, str):
try: try:
return value.encode(encoding) value = value.encode(encoding)
except UnicodeEncodeError: except UnicodeEncodeError:
value = value.encode('utf-8', 'replace') value = value.encode('utf-8', 'replace')
return value return value