Skip to content

Commit c701d38

Browse files
tobixenclaude
andauthored
style: ruff up things
* Reduce ruff ignore list: fix 12 rule categories Fixes and removes from pyproject.toml ignore list: - UP008: super() style (9 violations, auto-fixed) - UP045/UP007: Optional[X] type hints (16 violations, auto-fixed + dead code removed) - UP036: outdated sys.version_info check in tests (1 violation) - B011: assert False → raise AssertionError (4 violations) - B018: useless property accesses replaced with explicit method calls (6 violations) - B026: star-arg after keyword in Principal() call (1 violation) - B028: missing stacklevel= in warnings.warn() (1 violation) - B904: raise-from in except clauses (2 violations) - E721: == for type comparisons → is (5 violations) - E731: lambda assignments → def (4 violations) - B007, UP007, F403: were already clean Also removed dead code: TimeStamp type alias was silently undefined in calendarobjectresource.py, collection.py and davobject.py (try/except block was failing because `date` was never imported). Remaining ignore list annotated with violation counts and links to #634 Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 062395f commit c701d38

17 files changed

Lines changed: 70 additions & 96 deletions

caldav/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020

2121
warnings.warn(
2222
"You need to install the `build` package and do a `python -m build` "
23-
"to get caldav.__version__ set correctly"
23+
"to get caldav.__version__ set correctly",
24+
stacklevel=2,
2425
)
2526

2627
# Silence notification of no default logging handler

caldav/async_davclient.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,9 @@ def __init__(
155155
features: FeatureSet | dict | str | None = None,
156156
enable_rfc6764: bool = True,
157157
require_tls: bool = True,
158-
rate_limit_handle: Optional[bool] = None,
159-
rate_limit_default_sleep: Optional[int] = None,
160-
rate_limit_max_sleep: Optional[int] = None,
158+
rate_limit_handle: bool | None = None,
159+
rate_limit_default_sleep: int | None = None,
160+
rate_limit_max_sleep: int | None = None,
161161
) -> None:
162162
"""
163163
Initialize an async DAV client.

caldav/calendarobjectresource.py

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,13 @@
1717
import warnings
1818
from collections import defaultdict
1919
from datetime import datetime, timedelta, timezone
20-
from typing import TYPE_CHECKING, Any, Optional
20+
from typing import TYPE_CHECKING, Any, ClassVar, Optional
2121
from urllib.parse import ParseResult, SplitResult
2222

2323
import icalendar
2424
from dateutil.rrule import rrulestr
2525
from icalendar import vCalAddress, vText
2626

27-
try:
28-
from typing import ClassVar, Optional
29-
30-
TimeStamp = Optional[date | datetime]
31-
except:
32-
pass
33-
3427
if TYPE_CHECKING:
3528
from icalendar import vCalAddress
3629

@@ -142,9 +135,7 @@ def __init__(
142135
CalendarObjectResource has an additional parameter for its constructor:
143136
* data = "...", vCal data for the event
144137
"""
145-
super(CalendarObjectResource, self).__init__(
146-
client=client, url=url, parent=parent, id=id, props=props
147-
)
138+
super().__init__(client=client, url=url, parent=parent, id=id, props=props)
148139
if data is not None:
149140
self.data = data
150141
if id and self._get_component_type_cheap():
@@ -871,9 +862,9 @@ def _put(self, retry_on_failure=True):
871862
except ImportError:
872863
retry_on_failure = False
873864
if retry_on_failure:
874-
## This looks like a noop, but the object may be "cleaned".
865+
## Accessing vobject_instance may "clean" the object.
875866
## See https://github.com/python-caldav/caldav/issues/43
876-
self.vobject_instance
867+
self.get_vobject_instance()
877868
return self._put(False)
878869
else:
879870
raise error.PutError(errmsg(r))
@@ -895,7 +886,7 @@ async def _async_put(self, retry_on_failure=True):
895886
except ImportError:
896887
retry_on_failure = False
897888
if retry_on_failure:
898-
self.vobject_instance
889+
self.get_vobject_instance()
899890
return await self._async_put(False)
900891
else:
901892
raise error.PutError(errmsg(r))
@@ -950,7 +941,10 @@ def change_attendee_status(self, attendee: Any | None = None, **kwargs) -> None:
950941
attendee_lines = ical_obj["attendee"]
951942
if isinstance(attendee_lines, str):
952943
attendee_lines = [attendee_lines]
953-
strip_mailto = lambda x: str(x).lower().replace("mailto:", "")
944+
945+
def strip_mailto(x):
946+
return str(x).lower().replace("mailto:", "")
947+
954948
for attendee_line in attendee_lines:
955949
if strip_mailto(attendee_line) == strip_mailto(attendee):
956950
attendee_line.params.update(kwargs)
@@ -1855,7 +1849,7 @@ def is_pending(self, i=None) -> bool | None:
18551849
if i.get("STATUS", "NEEDS-ACTION") in ("CANCELLED", "COMPLETED"):
18561850
return False
18571851
## input data does not conform to the RFC
1858-
assert False
1852+
raise AssertionError
18591853

18601854
def uncomplete(self) -> None:
18611855
"""Undo completion - marks a completed task as not completed"""

caldav/collection.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,6 @@
2020

2121
import icalendar
2222

23-
try:
24-
from typing import Optional
25-
26-
TimeStamp = Optional[date | datetime]
27-
except:
28-
pass
29-
3023
if TYPE_CHECKING:
3124
from icalendar import vCalAddress
3225

@@ -252,7 +245,7 @@ def __init__(
252245
"""
253246
self._calendar_home_set = calendar_home_set
254247

255-
super(Principal, self).__init__(client=client, url=url, **kwargs)
248+
super().__init__(client=client, url=url, **kwargs)
256249
if url is None:
257250
if self.client is None:
258251
raise ValueError("Unexpected value None for self.client")
@@ -1819,7 +1812,7 @@ def __init__(
18191812
"""
18201813
Will locate the mbox if no url is given
18211814
"""
1822-
super(ScheduleMailbox, self).__init__(client=client, url=url)
1815+
super().__init__(client=client, url=url)
18231816
self._items = None
18241817
if not client and principal:
18251818
self.client = principal.client
@@ -1853,7 +1846,7 @@ def __init__(
18531846
# properly fix in a future revision
18541847
raise error.NotFoundError(
18551848
"principal has no %s. %s" % (str(self.findprop()), error.ERR_FRAGMENT) # type: ignore
1856-
)
1849+
) from None
18571850

18581851
def get_items(self):
18591852
"""

caldav/compatibility_hints.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ def set_feature(self, feature, value=True):
351351
elif value is None:
352352
fc = {feature: {"support": "unknown"}}
353353
else:
354-
assert False
354+
raise AssertionError
355355
self.copyFeatureSet(fc, collapse=False)
356356
feat_def = self.find_feature(feature)
357357
feat_type = feat_def.get('type', 'server-feature')
@@ -389,7 +389,7 @@ def copyFeatureSet(self, feature_set, collapse=True):
389389
self._validate_support_level(value['support'], feature)
390390
server_node.update(value)
391391
else:
392-
assert False
392+
raise AssertionError
393393
if collapse:
394394
self.collapse()
395395

@@ -598,12 +598,12 @@ def _convert_node(self, node, feature_info, return_type, accept_fragile=False):
598598
hierarchical dict, hence the naming of the method. I
599599
considered it too complicated though)
600600
"""
601-
if return_type == str:
601+
if return_type is str:
602602
## TODO: consider feature_info['type'], be smarter about it
603603
return node.get('support', node.get('enable', node.get('behaviour')))
604-
elif return_type == dict:
604+
elif return_type is dict:
605605
return node
606-
elif return_type == bool:
606+
elif return_type is bool:
607607
## TODO: consider feature_info['type'], be smarter about this
608608
support = node.get('support', 'full')
609609
if support == 'quirk':
@@ -616,7 +616,7 @@ def _convert_node(self, node, feature_info, return_type, accept_fragile=False):
616616
## TODO: this may be improved
617617
return not node.get('enable') and not node.get('behaviour') and not node.get('observed')
618618
else:
619-
assert False
619+
raise AssertionError
620620

621621
@classmethod
622622
def find_feature(cls, feature: str) -> dict:

caldav/config.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,9 @@ def read_config(fn, interactive_error=False):
108108
# Re-raise YAML errors so they can be handled by caller
109109
raise ValueError(f"config file {fn} is neither valid JSON nor YAML: {e}") from e
110110
except ImportError:
111-
raise ValueError(f"config file {fn} is not valid JSON, and pyyaml is not installed")
111+
raise ValueError(
112+
f"config file {fn} is not valid JSON, and pyyaml is not installed"
113+
) from None
112114

113115
except FileNotFoundError:
114116
## File not found

caldav/davclient.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,9 +211,9 @@ def __init__(
211211
features: FeatureSet | dict | str = None,
212212
enable_rfc6764: bool = True,
213213
require_tls: bool = True,
214-
rate_limit_handle: Optional[bool] = None,
215-
rate_limit_default_sleep: Optional[int] = None,
216-
rate_limit_max_sleep: Optional[int] = None,
214+
rate_limit_handle: bool | None = None,
215+
rate_limit_default_sleep: int | None = None,
216+
rate_limit_max_sleep: int | None = None,
217217
) -> None:
218218
"""
219219
Sets up a HTTPConnection object towards the server in the url.
@@ -453,7 +453,7 @@ def principal(self, *largs, **kwargs):
453453
calendars.
454454
"""
455455
if not self._principal:
456-
self._principal = Principal(client=self, *largs, **kwargs)
456+
self._principal = Principal(*largs, client=self, **kwargs)
457457
return self._principal
458458

459459
def calendar(self, **kwargs):

caldav/davobject.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,6 @@
66

77
from lxml import etree
88

9-
try:
10-
from typing import Optional
11-
12-
TimeStamp = Optional[date | datetime]
13-
except:
14-
pass
15-
169
if TYPE_CHECKING:
1710
from .davclient import DAVClient
1811

caldav/elements/base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,14 @@ def append(self, element: Self | Iterable[Self]) -> Self:
8282

8383
class NamedBaseElement(BaseElement):
8484
def __init__(self, name: str | None = None) -> None:
85-
super(NamedBaseElement, self).__init__(name=name)
85+
super().__init__(name=name)
8686

8787
def xmlelement(self):
8888
if self.attributes.get("name") is None:
8989
raise Exception("name attribute must be defined")
90-
return super(NamedBaseElement, self).xmlelement()
90+
return super().xmlelement()
9191

9292

9393
class ValuedBaseElement(BaseElement):
9494
def __init__(self, value: str | bytes | None = None) -> None:
95-
super(ValuedBaseElement, self).__init__(value=value)
95+
super().__init__(value=value)

caldav/elements/cdav.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ class TextMatch(ValuedBaseElement):
8888
tag: ClassVar[str] = ns("C", "text-match")
8989

9090
def __init__(self, value, collation: str = "i;octet", negate: bool = False) -> None:
91-
super(TextMatch, self).__init__(value=value)
91+
super().__init__(value=value)
9292

9393
if self.attributes is None:
9494
raise ValueError("Unexpected value None for self.attributes")
@@ -104,7 +104,7 @@ class TimeRange(BaseElement):
104104
def __init__(self, start: datetime | None = None, end: datetime | None = None) -> None:
105105
## start and end should be an icalendar "date with UTC time",
106106
## ref https://datatracker.ietf.org/doc/html/rfc4791#section-9.9
107-
super(TimeRange, self).__init__()
107+
super().__init__()
108108

109109
if self.attributes is None:
110110
raise ValueError("Unexpected value None for self.attributes")
@@ -128,7 +128,7 @@ class Expand(BaseElement):
128128
tag: ClassVar[str] = ns("C", "expand")
129129

130130
def __init__(self, start: datetime | None, end: datetime | None = None) -> None:
131-
super(Expand, self).__init__()
131+
super().__init__()
132132

133133
if self.attributes is None:
134134
raise ValueError("Unexpected value None for self.attributes")

0 commit comments

Comments
 (0)