From 018ffc29becd94325cf5842163dcea6c875bb1db Mon Sep 17 00:00:00 2001 From: RiccardoBifulco Date: Fri, 20 Nov 2026 20:40:59 +0100 Subject: [PATCH] Add ical_value property to vRecur The property returns the rule parts as a plain dict of native Python values, so Component.decoded("RRULE") no longer returns a vRecur. Part of #876. --- news/876.feature.3 | 1 + src/icalendar/prop/recur/recur.py | 39 ++++++++++++++ .../tests/prop/test_vRecur_ical_value.py | 54 +++++++++++++++++++ src/icalendar/tests/test_parsing.py | 12 +++-- 4 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 news/876.feature.3 create mode 100644 src/icalendar/tests/prop/test_vRecur_ical_value.py diff --git a/news/876.feature.3 b/news/876.feature.3 new file mode 100644 index 000000000..f94e21961 --- /dev/null +++ b/news/876.feature.3 @@ -0,0 +1 @@ +Created the :attr:`vRecur.ical_value ` property. :meth:`Component.decoded() ` now returns a plain :class:`dict` of native Python values for ``RRULE`` instead of a :class:`~icalendar.prop.recur.recur.vRecur`. I used AI to help with this change. @RiccardoBifulco diff --git a/src/icalendar/prop/recur/recur.py b/src/icalendar/prop/recur/recur.py index 3f6b6a33d..abefc9851 100644 --- a/src/icalendar/prop/recur/recur.py +++ b/src/icalendar/prop/recur/recur.py @@ -2,6 +2,7 @@ from __future__ import annotations +from enum import Enum from typing import TYPE_CHECKING, Any, ClassVar from xml.etree.ElementTree import Element, SubElement @@ -264,6 +265,44 @@ def from_ical(cls, ical: str): except Exception as e: raise ValueError(f"Error in recurrence rule: {ical}") from e + @property + def ical_value(self) -> dict[str, list[Any]]: + """The rule parts as a plain :class:`dict` of native Python values. + + Each key is the name of a rule part, for example ``FREQ`` or ``BYDAY``. + Each value is a list of native Python values, such as :class:`str`, + :class:`int`, :class:`~datetime.date` or :class:`~datetime.datetime`. + The result is a copy: changing it does not modify this recurrence. + + .. code-block:: pycon + + >>> from icalendar.prop import vRecur + >>> vRecur.from_ical("FREQ=WEEKLY;COUNT=3;BYDAY=MO,TU").ical_value + {'FREQ': ['WEEKLY'], 'COUNT': [3], 'BYDAY': ['MO', 'TU']} + + See Also: + + :rfc:`5545#section-3.3.10` for the ``RECUR`` value type. + """ + return { + key: [ + self._native_value(v) + for v in (values if isinstance(values, SEQUENCE_TYPES) else [values]) + ] + for key, values in self.items() + } + + @staticmethod + def _native_value(value: Any) -> Any: + """Return the native Python value of one rule part value.""" + if isinstance(value, Enum): + return str(value.value) + if hasattr(value, "ical_value"): + return value.ical_value + if isinstance(value, int): + return int(value) + return value + @classmethod def examples(cls) -> list[Self]: """Examples of vRecur.""" diff --git a/src/icalendar/tests/prop/test_vRecur_ical_value.py b/src/icalendar/tests/prop/test_vRecur_ical_value.py new file mode 100644 index 000000000..24295884f --- /dev/null +++ b/src/icalendar/tests/prop/test_vRecur_ical_value.py @@ -0,0 +1,54 @@ +"""Test vRecur.ical_value, see issue 876.""" + +from datetime import date, datetime + +from icalendar import Event +from icalendar.prop import vRecur + + +def test_ical_value_native_values(): + """The rule parts are returned as native Python values.""" + recur = vRecur.from_ical("FREQ=WEEKLY;COUNT=3;BYDAY=1SU,MO;BYMONTH=11;WKST=MO") + value = recur.ical_value + assert value == { + "FREQ": ["WEEKLY"], + "COUNT": [3], + "BYDAY": ["1SU", "MO"], + "BYMONTH": [11], + "WKST": ["MO"], + } + assert type(value) is dict + assert type(value["FREQ"][0]) is str + assert type(value["COUNT"][0]) is int + assert type(value["BYMONTH"][0]) is int + + +def test_ical_value_until(): + """UNTIL is a date or a datetime.""" + assert vRecur.from_ical("FREQ=DAILY;UNTIL=20240102").ical_value["UNTIL"] == [ + date(2024, 1, 2) + ] + assert vRecur.from_ical("FREQ=DAILY;UNTIL=20240102T030405").ical_value["UNTIL"] == [ + datetime(2024, 1, 2, 3, 4, 5) + ] + + +def test_ical_value_skip_and_rscale(): + """RFC 7529 parts are plain strings.""" + value = vRecur.from_ical("RSCALE=GREGORIAN;FREQ=YEARLY;SKIP=FORWARD").ical_value + assert value == {"RSCALE": ["GREGORIAN"], "FREQ": ["YEARLY"], "SKIP": ["FORWARD"]} + assert type(value["SKIP"][0]) is str + + +def test_ical_value_is_a_copy(): + """Changing the result does not change the recurrence.""" + recur = vRecur.from_ical("FREQ=DAILY;COUNT=2") + recur.ical_value["COUNT"].append(5) + assert recur.to_ical() == b"FREQ=DAILY;COUNT=2" + + +def test_decoded_uses_ical_value(): + """Component.decoded() returns the native values.""" + event = Event() + event.add("RRULE", {"FREQ": "DAILY", "COUNT": 2}) + assert event.decoded("RRULE") == {"FREQ": ["DAILY"], "COUNT": [2]} diff --git a/src/icalendar/tests/test_parsing.py b/src/icalendar/tests/test_parsing.py index 472e467bd..87005cae1 100644 --- a/src/icalendar/tests/test_parsing.py +++ b/src/icalendar/tests/test_parsing.py @@ -5,7 +5,7 @@ import pytest -from icalendar import vBinary, vRecur +from icalendar import vBinary from icalendar.cal.calendar import Calendar from icalendar.cal.component_factory import ComponentFactory from icalendar.cal.event import Event @@ -108,8 +108,7 @@ def test_issue_157_removes_trailing_semicolon(events): https://github.com/PyCalendar/icalendar/pull/157 """ recur = events.issue_157_removes_trailing_semicolon.decoded("RRULE") - assert isinstance(recur, vRecur) - assert recur.to_ical() == b"FREQ=YEARLY;BYDAY=1SU;BYMONTH=11" + assert recur == {"FREQ": ["YEARLY"], "BYDAY": ["1SU"], "BYMONTH": [11]} @pytest.mark.parametrize( @@ -135,8 +134,11 @@ def test_decode_rrule_attribute_error_issue_70(events): # Issue #70 - e.decode("RRULE") causes Attribute Error # see https://github.com/PyCalendar/icalendar/issues/70 recur = events.issue_70_rrule_causes_attribute_error.decoded("RRULE") - assert isinstance(recur, vRecur) - assert recur.to_ical() == b"FREQ=WEEKLY;UNTIL=20070619T225959;INTERVAL=1" + assert recur == { + "FREQ": ["WEEKLY"], + "UNTIL": [datetime(2007, 6, 19, 22, 59, 59)], + "INTERVAL": [1], + } def test_description_parsed_properly_issue_53(events):