Cleaned up type-error fix

pull/581/head
bcapuano 2023-11-04 12:37:45 -04:00
rodzic bb684ec5cd
commit 41afc2c7d2
2 zmienionych plików z 20 dodań i 15 usunięć

Wyświetl plik

@ -2,6 +2,23 @@ SEQUENCE_TYPES = (list, tuple)
DEFAULT_ENCODING = 'utf-8'
def from_unicode(value, encoding='utf-8') -> bytes:
"""
Converts a value to bytes, even if it already is bytes
:param value: The value to convert
:param encoding: The encoding to use in the conversion
:return: The bytes representation of the value
"""
if isinstance(value, bytes):
return value
elif isinstance(value, str):
try:
return value.encode(encoding)
except UnicodeEncodeError:
value = value.encode('utf-8', 'replace')
return value
def to_unicode(value, encoding='utf-8'):
"""Converts a value to unicode, even if it is already a unicode string.
"""

Wyświetl plik

@ -53,6 +53,7 @@ from icalendar.parser import unescape_char
from icalendar.parser_tools import DEFAULT_ENCODING
from icalendar.parser_tools import SEQUENCE_TYPES
from icalendar.parser_tools import to_unicode
from icalendar.parser_tools import from_unicode
from icalendar.timezone_cache import _timezone_cache
from icalendar.windows_to_olson import WINDOWS_TO_OLSON
@ -251,21 +252,8 @@ class vDDDLists:
self.dts = vDDD
def to_ical(self):
dts_ical = [dt.to_ical() for dt in self.dts]
# Make sure all elements are of the same type
if dts_ical and all(isinstance(dt, type(dts_ical[0])) for dt in dts_ical):
first_dt = dts_ical[0]
if isinstance(first_dt, bytes):
return b",".join(dts_ical)
elif isinstance(first_dt, str):
return ",".join(dts_ical)
else:
raise ValueError(f"Unexpected type {type(first_dt)} in vDDD list!")
elif not dts_ical:
return b""
else:
raise ValueError("Type mismatch in vDDD list!")
dts_ical = (from_unicode(dt.to_ical()) for dt in self.dts)
return b",".join(dts_ical)
@staticmethod
def from_ical(ical, timezone=None):