Skip to content

Help classes

Sometimes properties have a lot in common. Instead of constantly redefining all methods, we simply create an abstraction from the properties which we call help classes.

This is the list of all help classes.

_IntProperty

Bases: Property

This property class should be inherited. It represents a property that contain just an int as value.

Source code in ical_library/ical_properties/ints.py
 4
 5
 6
 7
 8
 9
10
class _IntProperty(Property):
    """This property class should be inherited. It represents a property that contain just an int as value."""

    @property
    def int_value(self) -> int:
        """Return the value as an int."""
        return int(self.value)

int_value: int property

Return the value as an int.

_DTBoth

Bases: Property

This property class should be inherited. It represents a property that contain a datetime or date as value.

Source code in ical_library/ical_properties/dt.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class _DTBoth(Property):
    """This property class should be inherited. It represents a property that contain a datetime or date as value."""

    @property
    def datetime_or_date_value(self) -> Union[Date, DateTime]:
        """Return the value as a DateTime or Date value taking into account the optional TZID property parameter."""
        value = dt_utils.parse_date_or_datetime(self.value)
        if isinstance(value, DateTime):
            tz_id = self.get_property_parameter("TZID")
            if value.tz or not tz_id:
                return value
            return self.parent.tree_root.get_aware_dt_for_timezone(dt=value, tzid=tz_id)
        elif isinstance(value, Date):
            return value
        else:
            raise TypeError(f"Unknown {type(value)=} returned for {value=}.")

    def get_datetime_or_date_value_in_specific_tz(self, tz: FixedTimezone) -> Union[Date, DateTime]:
        """Return the value as a DateTime or Date value in a specific timezone."""
        value = dt_utils.parse_date_or_datetime(self.value)
        if isinstance(value, DateTime):
            return value.in_timezone(tz)
        elif isinstance(value, Date):
            return value
        else:
            raise TypeError(f"Unknown {type(value)=} returned for {value=}.")

datetime_or_date_value: Union[Date, DateTime] property

Return the value as a DateTime or Date value taking into account the optional TZID property parameter.

get_datetime_or_date_value_in_specific_tz(tz)

Return the value as a DateTime or Date value in a specific timezone.

Source code in ical_library/ical_properties/dt.py
28
29
30
31
32
33
34
35
36
def get_datetime_or_date_value_in_specific_tz(self, tz: FixedTimezone) -> Union[Date, DateTime]:
    """Return the value as a DateTime or Date value in a specific timezone."""
    value = dt_utils.parse_date_or_datetime(self.value)
    if isinstance(value, DateTime):
        return value.in_timezone(tz)
    elif isinstance(value, Date):
        return value
    else:
        raise TypeError(f"Unknown {type(value)=} returned for {value=}.")

_DTSingular

Bases: Property

This property class should be inherited. It represents a property that can only contain a datetime as value.

Source code in ical_library/ical_properties/dt.py
39
40
41
42
43
44
45
46
47
48
49
class _DTSingular(Property):
    """This property class should be inherited. It represents a property that can only contain a datetime as value."""

    @property
    def datetime(self) -> DateTime:
        """Return the value as a DateTime value taking into account the optional TZID property parameter."""
        value = pendulum.parse(self.value, tz=None)
        tz_id = self.get_property_parameter("TZID")
        if value.tz or not tz_id:
            return value
        return self.parent.tree_root.get_aware_dt_for_timezone(dt=value, tzid=tz_id)

datetime: DateTime property

Return the value as a DateTime value taking into account the optional TZID property parameter.

_CalAddress

Bases: Property

Source code in ical_library/ical_properties/cal_address.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class _CalAddress(Property):
    @property
    def persons_name(self) -> Optional[str]:
        """Return the persons name, identified by the CN property parameter."""
        return self.get_property_parameter("CN")

    @property
    def email(self) -> Optional[str]:
        """Return the email if the value starts with `mailto:`. Otherwise return None."""
        if self.value.startswith("mailto:"):
            return self.value[len("mailto:") :]
        return None

    @property
    def cu_type(self) -> str:
        """Return the CUTYPE."""
        return self.get_property_parameter_default("CUTYPE", default="INDIVIDUAL")

    @property
    def member(self) -> Optional[str]:
        """Return the membership property parameter."""
        return self.get_property_parameter("MEMBER")

    @property
    def role(self) -> str:
        """Return the role of the person."""
        return self.get_property_parameter_default("ROLE", default="REQ-PARTICIPANT")

    @property
    def participation_status(self) -> str:
        """Return the participation status, indicating whether the person will be present or not."""
        return self.get_property_parameter_default("PARTSTAT", default="NEEDS-ACTION")

cu_type: str property

Return the CUTYPE.

email: Optional[str] property

Return the email if the value starts with mailto:. Otherwise return None.

member: Optional[str] property

Return the membership property parameter.

participation_status: str property

Return the participation status, indicating whether the person will be present or not.

persons_name: Optional[str] property

Return the persons name, identified by the CN property parameter.

role: str property

Return the role of the person.

_PeriodFunctionality

Bases: Property

Provide methods to help to parse duration values.

This class should be inherited by a Property.

Source code in ical_library/ical_properties/periods.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class _PeriodFunctionality(Property):
    """
    Provide methods to help to parse duration values.

    This class should be inherited by a Property.
    """

    def _parse_period_values(self) -> List[Tuple[DateTime, DateTime]]:
        """
        Parse multiple values, delimited by comma's, representing periods.

        Example value for self.value: 19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H
        :return: List of tuples containing two DateTimes representing the start and end of the duration respectively.
        """
        list_of_periods: List[Tuple[DateTime, DateTime]] = []
        for item in self.value.split(","):
            item = item.strip()
            instance = self._parse_individual_duration_str(item)
            if not isinstance(instance, tuple) or len(instance) != 2:
                raise TypeError(f"{instance} is of {type(instance)=} while it should be a tuple.")
            for index, sub_instance in enumerate(instance):
                if not isinstance(sub_instance, DateTime):
                    raise TypeError(
                        f"{instance[index]=} is of {type(sub_instance)=} while it should be of type "
                        f"Tuple[DateTime, DateTime]."
                    )
            list_of_periods.append(instance)
        return list_of_periods

    def _parse_individual_datetime_or_duration_str(self, datetime_or_duration_str: str) -> Union[DateTime, Duration]:
        """
        Parse an individual datetime or duration string.
        :param datetime_or_duration_str: A string represent either a datetime or duration.
        :return: A pendulum.DateTime if the string represented a datetime. Return a pendulum.Duration otherwise.
        """
        tz_id = self.get_property_parameter("TZID")
        tz = self.parent.tree_root.get_timezone(tz_id).get_as_timezone_object() if tz_id else None
        return pendulum.parse(datetime_or_duration_str, tz=tz)

    def _parse_individual_duration_str(self, period_str: str) -> Tuple[DateTime, DateTime]:
        """
        Parse an individual period represented by DateTime/DateTime or DateTime/Duration.

        :param period_str: The period to parse. Examples: 19960403T020000Z/19960403T040000Z or 19960404T010000Z/PT3H
        :return: A tuple containing two DateTimes representing the start and end of the duration respectively.
        """
        first_str, second_str = period_str.split("/")
        first_instance: DateTime = self._parse_individual_datetime_or_duration_str(first_str)
        second_instance: Union[DateTime, Duration] = self._parse_individual_datetime_or_duration_str(second_str)
        if not isinstance(first_instance, DateTime):
            raise TypeError(f"Expected {period_str=} to contain a DateTime as first argument.")
        if isinstance(second_instance, DateTime):
            return first_instance, second_instance
        elif isinstance(second_instance, Duration):
            computed_datetime: DateTime = first_instance + second_instance  # type: ignore  # Pendulum at fault
            return first_instance, computed_datetime
        else:
            raise TypeError(f"Expected {period_str=} to contain a DateTime or Duration as second argument.")

_parse_individual_datetime_or_duration_str(datetime_or_duration_str)

Parse an individual datetime or duration string.

Parameters:

Name Type Description Default
datetime_or_duration_str str

A string represent either a datetime or duration.

required

Returns:

Type Description
Union[DateTime, Duration]

A pendulum.DateTime if the string represented a datetime. Return a pendulum.Duration otherwise.

Source code in ical_library/ical_properties/periods.py
39
40
41
42
43
44
45
46
47
def _parse_individual_datetime_or_duration_str(self, datetime_or_duration_str: str) -> Union[DateTime, Duration]:
    """
    Parse an individual datetime or duration string.
    :param datetime_or_duration_str: A string represent either a datetime or duration.
    :return: A pendulum.DateTime if the string represented a datetime. Return a pendulum.Duration otherwise.
    """
    tz_id = self.get_property_parameter("TZID")
    tz = self.parent.tree_root.get_timezone(tz_id).get_as_timezone_object() if tz_id else None
    return pendulum.parse(datetime_or_duration_str, tz=tz)

_parse_individual_duration_str(period_str)

Parse an individual period represented by DateTime/DateTime or DateTime/Duration.

Parameters:

Name Type Description Default
period_str str

The period to parse. Examples: 19960403T020000Z/19960403T040000Z or 19960404T010000Z/PT3H

required

Returns:

Type Description
Tuple[DateTime, DateTime]

A tuple containing two DateTimes representing the start and end of the duration respectively.

Source code in ical_library/ical_properties/periods.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def _parse_individual_duration_str(self, period_str: str) -> Tuple[DateTime, DateTime]:
    """
    Parse an individual period represented by DateTime/DateTime or DateTime/Duration.

    :param period_str: The period to parse. Examples: 19960403T020000Z/19960403T040000Z or 19960404T010000Z/PT3H
    :return: A tuple containing two DateTimes representing the start and end of the duration respectively.
    """
    first_str, second_str = period_str.split("/")
    first_instance: DateTime = self._parse_individual_datetime_or_duration_str(first_str)
    second_instance: Union[DateTime, Duration] = self._parse_individual_datetime_or_duration_str(second_str)
    if not isinstance(first_instance, DateTime):
        raise TypeError(f"Expected {period_str=} to contain a DateTime as first argument.")
    if isinstance(second_instance, DateTime):
        return first_instance, second_instance
    elif isinstance(second_instance, Duration):
        computed_datetime: DateTime = first_instance + second_instance  # type: ignore  # Pendulum at fault
        return first_instance, computed_datetime
    else:
        raise TypeError(f"Expected {period_str=} to contain a DateTime or Duration as second argument.")

_parse_period_values()

Parse multiple values, delimited by comma's, representing periods.

Example value for self.value: 19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H

Returns:

Type Description
List[Tuple[DateTime, DateTime]]

List of tuples containing two DateTimes representing the start and end of the duration respectively.

Source code in ical_library/ical_properties/periods.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def _parse_period_values(self) -> List[Tuple[DateTime, DateTime]]:
    """
    Parse multiple values, delimited by comma's, representing periods.

    Example value for self.value: 19960403T020000Z/19960403T040000Z,19960404T010000Z/PT3H
    :return: List of tuples containing two DateTimes representing the start and end of the duration respectively.
    """
    list_of_periods: List[Tuple[DateTime, DateTime]] = []
    for item in self.value.split(","):
        item = item.strip()
        instance = self._parse_individual_duration_str(item)
        if not isinstance(instance, tuple) or len(instance) != 2:
            raise TypeError(f"{instance} is of {type(instance)=} while it should be a tuple.")
        for index, sub_instance in enumerate(instance):
            if not isinstance(sub_instance, DateTime):
                raise TypeError(
                    f"{instance[index]=} is of {type(sub_instance)=} while it should be of type "
                    f"Tuple[DateTime, DateTime]."
                )
        list_of_periods.append(instance)
    return list_of_periods

_ExOrRDate

Bases: _PeriodFunctionality

Provide methods to help to parse different kind of values a Property could find.

This class should be inherited by a Property.

Source code in ical_library/ical_properties/periods.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
class _ExOrRDate(_PeriodFunctionality):
    """
    Provide methods to help to parse different kind of values a Property could find.

    This class should be inherited by a Property.
    """

    def _parse_datetime_values(self) -> List[DateTime]:
        """
        Parses DateTime values. Example of a possible value of self.value: 19970714T123000Z,19970714T123300Z
        :return: A List of DateTimes representing the start of an event/component.
        """
        list_of_datetimes: List[DateTime] = []
        for item in self.value.split(","):
            item = item.strip()
            instance = self._parse_individual_datetime_or_duration_str(item)
            if not isinstance(instance, DateTime):
                raise TypeError(f"{instance} is of {type(instance)=} while it should be a DateTime.")
            list_of_datetimes.append(instance)
        return list_of_datetimes

    def _parse_date_values(self) -> List[Date]:
        """
        Parse Date values. Example of a possible value of self.value: 19970101,19970120,19970217
        :return: A list of pendulum.Date representing the start of an event/component.
        """
        list_of_dates: List[Date] = []
        for item in self.value.split(","):
            instance = self._parse_individual_date_str(item)
            if not isinstance(instance, Date):
                raise TypeError(f"{instance} is of {type(instance)=} while it should be a Date.")
            list_of_dates.append(instance)
        return list_of_dates

    @staticmethod
    def _parse_individual_date_str(date: str) -> Date:
        """
        Parse an individual date string.
        :param date: A string representing a date.
        :return: A pendulum.Date.
        """
        return Date(int(date[0:4]), int(date[4:6]), int(date[6:8]))

_parse_date_values()

Parse Date values. Example of a possible value of self.value: 19970101,19970120,19970217

Returns:

Type Description
List[Date]

A list of pendulum.Date representing the start of an event/component.

Source code in ical_library/ical_properties/periods.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def _parse_date_values(self) -> List[Date]:
    """
    Parse Date values. Example of a possible value of self.value: 19970101,19970120,19970217
    :return: A list of pendulum.Date representing the start of an event/component.
    """
    list_of_dates: List[Date] = []
    for item in self.value.split(","):
        instance = self._parse_individual_date_str(item)
        if not isinstance(instance, Date):
            raise TypeError(f"{instance} is of {type(instance)=} while it should be a Date.")
        list_of_dates.append(instance)
    return list_of_dates

_parse_datetime_values()

Parses DateTime values. Example of a possible value of self.value: 19970714T123000Z,19970714T123300Z

Returns:

Type Description
List[DateTime]

A List of DateTimes representing the start of an event/component.

Source code in ical_library/ical_properties/periods.py
77
78
79
80
81
82
83
84
85
86
87
88
89
def _parse_datetime_values(self) -> List[DateTime]:
    """
    Parses DateTime values. Example of a possible value of self.value: 19970714T123000Z,19970714T123300Z
    :return: A List of DateTimes representing the start of an event/component.
    """
    list_of_datetimes: List[DateTime] = []
    for item in self.value.split(","):
        item = item.strip()
        instance = self._parse_individual_datetime_or_duration_str(item)
        if not isinstance(instance, DateTime):
            raise TypeError(f"{instance} is of {type(instance)=} while it should be a DateTime.")
        list_of_datetimes.append(instance)
    return list_of_datetimes

_parse_individual_date_str(date) staticmethod

Parse an individual date string.

Parameters:

Name Type Description Default
date str

A string representing a date.

required

Returns:

Type Description
Date

A pendulum.Date.

Source code in ical_library/ical_properties/periods.py
104
105
106
107
108
109
110
111
@staticmethod
def _parse_individual_date_str(date: str) -> Date:
    """
    Parse an individual date string.
    :param date: A string representing a date.
    :return: A pendulum.Date.
    """
    return Date(int(date[0:4]), int(date[4:6]), int(date[6:8]))

_TZOffset

Bases: Property

Helper class to represent a UTC offset. This class should be inherited.

Add functions to parse the value as a fixed timezone offset.

Source code in ical_library/ical_properties/tz_offset.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class _TZOffset(Property):
    """
    Helper class to represent a UTC offset. This class should be inherited.

    Add functions to parse the value as a fixed timezone offset.
    """

    def parse_value_as_seconds(self) -> int:
        """Parse the value as seconds difference from UTC."""
        plus_or_minus = self.value[0]
        hour = int(self.value[1:3])
        minute = int(self.value[3:5])
        seconds = int(self.value[5:7]) if len(self.value) > 6 else 0
        summed = seconds + 60 * (minute + 60 * hour)
        return summed if plus_or_minus == "+" else 0 - summed

    def as_timezone_object(self) -> FixedTimezone:
        """Return the value of the property as a fixed timezone offset."""
        return FixedTimezone(self.parse_value_as_seconds())

as_timezone_object()

Return the value of the property as a fixed timezone offset.

Source code in ical_library/ical_properties/tz_offset.py
22
23
24
def as_timezone_object(self) -> FixedTimezone:
    """Return the value of the property as a fixed timezone offset."""
    return FixedTimezone(self.parse_value_as_seconds())

parse_value_as_seconds()

Parse the value as seconds difference from UTC.

Source code in ical_library/ical_properties/tz_offset.py
13
14
15
16
17
18
19
20
def parse_value_as_seconds(self) -> int:
    """Parse the value as seconds difference from UTC."""
    plus_or_minus = self.value[0]
    hour = int(self.value[1:3])
    minute = int(self.value[3:5])
    seconds = int(self.value[5:7]) if len(self.value) > 6 else 0
    summed = seconds + 60 * (minute + 60 * hour)
    return summed if plus_or_minus == "+" else 0 - summed