Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/876.feature.3
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Created the :attr:`vRecur.ical_value <icalendar.prop.recur.recur.vRecur.ical_value>` property. :meth:`Component.decoded() <icalendar.cal.component.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
39 changes: 39 additions & 0 deletions src/icalendar/prop/recur/recur.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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."""
Expand Down
54 changes: 54 additions & 0 deletions src/icalendar/tests/prop/test_vRecur_ical_value.py
Original file line number Diff line number Diff line change
@@ -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]}
12 changes: 7 additions & 5 deletions src/icalendar/tests/test_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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):
Expand Down