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/1930.documentation.1
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added value type hints to :class:`~icalendar.prop.recur.recur.vRecur`. Also updated the ``CaselessDict.canonical_order`` type annotation to support subclass key ordering. @Gabriel2002Can

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if type hints are documentation.
Can you check with other entries in the changelog where type hints appear?

2 changes: 1 addition & 1 deletion src/icalendar/caselessdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def __ne__(self, other: object) -> bool:

# A list of keys that must appear first in sorted_keys and sorted_items;
# must be uppercase.
canonical_order = None
canonical_order: Iterable[str] | None = None

def sorted_keys(self) -> list[str]:
"""Sort keys according to the canonical order for this class.
Expand Down
47 changes: 33 additions & 14 deletions src/icalendar/prop/recur/recur.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Any, ClassVar
from datetime import date, datetime, time, timedelta
from typing import TYPE_CHECKING, Any, ClassVar, TypeAlias, cast
from xml.etree.ElementTree import Element, SubElement

from icalendar.caselessdict import CaselessDict
Expand All @@ -26,8 +27,21 @@
from icalendar.parser.xcal.base import XCalParser
from icalendar.prop import VPROPERTY

RecurValue: TypeAlias = (
int
| str
| date
| datetime
| time
| timedelta
| tuple[datetime, datetime | timedelta]
| vDDDTypes
)

class vRecur(CaselessDict):
RecurEntryValue: TypeAlias = RecurValue | list[RecurValue] | tuple[RecurValue, ...]


class vRecur(CaselessDict[RecurEntryValue]):
"""Recurrence definition.

Property Name:
Expand Down Expand Up @@ -147,7 +161,10 @@ class vRecur(CaselessDict):
)

types: ClassVar[
dict[str, type[vInt | vMonth | vFrequency | vWeekday | vSkip | vText]]
dict[
str,
type[vInt | vMonth | vDDDTypes | vFrequency | vWeekday | vSkip | vText],
]
] = CaselessDict(
{
"COUNT": vNonNegativeInt,
Expand Down Expand Up @@ -187,10 +204,10 @@ def __init__(
super().__init__(*args, **kwargs)
self.params = Parameters(params)

def to_ical(self):
def to_ical(self) -> bytes:
result = []
for key, vals in self.sorted_items():
typ = self.types.get(key, vText)
typ: Any = self.types.get(key, vText)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, this is nice. Since it you already typed the dict, maybe this is not required?

Suggested change
typ: Any = self.types.get(key, vText)
typ = self.types.get(key, vText)

if not isinstance(vals, SEQUENCE_TYPES):
vals = [vals]
param_vals = b",".join(typ(val).to_ical() for val in vals)
Expand All @@ -202,7 +219,7 @@ def to_ical(self):
return b";".join(result)

@classmethod
def parse_type(cls, key, values):
def parse_type(cls, key: str, values: str) -> list[RecurValue]:
# integers
parser = cls.types.get(key, vText)
return [parser.from_ical(v) for v in values.split(",")]
Expand Down Expand Up @@ -236,11 +253,11 @@ def examples(cls) -> list[Self]:

def to_jcal(self, name: str) -> list:
"""The jCal representation of this property according to :rfc:`7265`."""
recur = {}
recur: dict[str, Any] = {}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing wise, we can assume here that all values are JSON compatible.
Any is good enough.

If you want to make it perfect: https://datatracker.ietf.org/doc/html/rfc7265#section-3.6.10

No need to change it though.

for k, v in self.items():
key = k.lower()
if key.upper() in self.jcal_not_a_list:
value = v[0] if isinstance(v, list) and len(v) == 1 else v
value: Any = v[0] if isinstance(v, list) and len(v) == 1 else v
elif not isinstance(v, list):
value = [v]
else:
Expand Down Expand Up @@ -273,15 +290,16 @@ def from_jcal(cls, jcal_property: list) -> Self:
3,
value=jcal_property[3],
)
recur = {}
recur: dict[str, RecurValue | list[RecurValue]] = {}
for key, value in jcal_property[3].items():
JCalParsingError.validate_jcal_token(
key, "recurrence rule part name", cls, path=[3, key]
)
value_type = cls.types.get(key, vText)
with JCalParsingError.reraise_with_path_added(3, key):
if isinstance(value, list):
recur[key.lower()] = values = []
values: list[RecurValue] = []
recur[key.lower()] = values
for i, v in enumerate(value):
with JCalParsingError.reraise_with_path_added(i):
values.append(value_type.parse_jcal_value(v))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be a follow-up if you like in another PR. It might need the type hints to be stored somewhere else to avoid circular imports or maybe the functions can just return an explicit type that is compatible.

Expand Down Expand Up @@ -333,7 +351,7 @@ def count(self) -> int | None:
return None
value = values[0] if isinstance(values, SEQUENCE_TYPES) else values
try:
return int(value)
return int(cast("int | str", value))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you use a string here?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably, it is clear that if that does not work, then we could also guide this with a isinstance check. But I think, it is wrong because the TypeError is caught below.

except (TypeError, ValueError) as e:
# Matches how icalendar.attr.single_int_property surfaces a stored
# value that is not readable as an int.
Expand Down Expand Up @@ -469,16 +487,17 @@ def from_xcal(cls, parser: XCalParser, params: Parameters) -> Self:
if from_xcal is None:
from_xcal = v_prop.from_xcal
value = from_xcal(parser)
self.setdefault(key, []).append(value)
values = cast("list[RecurValue]", self.setdefault(key, []))
values.append(cast("RecurValue", value))
return self

def to_xcal(self, element: Element) -> None:
"""Add the xCal representation of this property according to :rfc:`6321`."""
self.params.to_xcal(element)
recur_element = SubElement(element, self.default_value.lower())
for key, value in self.sorted_items():
value = value if isinstance(value, list) else [value]
for v in value:
values: list[Any] = value if isinstance(value, list) else [value]
for v in values:
if not hasattr(v, "to_xcal"):
v_prop = self.types.get(key, vText)
v = v_prop(v)
Expand Down
17 changes: 17 additions & 0 deletions src/icalendar/tests/test_issue_1930.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from typing_extensions import assert_type

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think, typing_extensions might not always be installed?
It would live in icalendar.compatibility with a Python version check.


from icalendar.prop.recur.recur import RecurEntryValue, vRecur


def test_vrecur_value_type():
rule = vRecur.from_ical("FREQ=DAILY;COUNT=10")

assert_type(rule["COUNT"], RecurEntryValue)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure what the difference here is to isinstance. Can you help me understand?

assert rule["COUNT"] == [10]


def test_vrecur_value_type_with_multiple_values():
rule = vRecur.from_ical("FREQ=DAILY;BYDAY=MO,TU,WE")

assert_type(rule["BYDAY"], RecurEntryValue)
assert rule["BYDAY"] == ["MO", "TU", "WE"]
Loading