Skip to content

Commit

Permalink
Cleaned up type-error fix
Browse files Browse the repository at this point in the history
  • Loading branch information
capuanob committed Nov 4, 2023
1 parent bb684ec commit 41afc2c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
17 changes: 17 additions & 0 deletions src/icalendar/parser_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,23 @@
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.
"""
Expand Down
18 changes: 3 additions & 15 deletions src/icalendar/prop.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
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

Expand Down Expand Up @@ -251,21 +252,8 @@ def __init__(self, dt_list):
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):
Expand Down

0 comments on commit 41afc2c

Please sign in to comment.