Repository navigation
Issue 1930 #1964
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Issue 1930 #1964
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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 | ||||||
|
|
@@ -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: | ||||||
|
|
@@ -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, | ||||||
|
|
@@ -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) | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
|
||||||
| if not isinstance(vals, SEQUENCE_TYPES): | ||||||
| vals = [vals] | ||||||
| param_vals = b",".join(typ(val).to_ical() for val in vals) | ||||||
|
|
@@ -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(",")] | ||||||
|
|
@@ -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] = {} | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Typing wise, we can assume here that all values are JSON compatible. 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: | ||||||
|
|
@@ -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)) | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||||||
|
|
@@ -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)) | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why do you use a string here?
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||||||
|
|
@@ -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) | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| from typing_extensions import assert_type | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think, typing_extensions might not always be installed? |
||
|
|
||
| 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) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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"] | ||
There was a problem hiding this comment.
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?