Skip to content

Commit

Permalink
Improved converters and type annotations (#1014)
Browse files Browse the repository at this point in the history
* Add proper type annotations to converters and fix `None` case for `as_timezone()`
* Swap order of `timezone` parameter type annotation for `CronTrigger.from_crontab()`
* Access enum member by name without using `__members__`
  • Loading branch information
injust authored Jan 12, 2025
1 parent 74a5ba4 commit 8548e7f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 13 deletions.
21 changes: 9 additions & 12 deletions src/apscheduler/_converters.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
from __future__ import annotations

from collections.abc import Callable
from datetime import date, datetime, timedelta, timezone
from datetime import date, datetime, timedelta, timezone, tzinfo
from typing import Any
from uuid import UUID
from zoneinfo import ZoneInfo

from tzlocal import get_localzone


def as_int(value: Any) -> Any:
def as_int(value: int | str) -> int:
if isinstance(value, str):
return int(value)

return value


def as_aware_datetime(value: Any) -> Any:
def as_aware_datetime(value: datetime | str) -> datetime:
if isinstance(value, str):
# Before Python 3.11, fromisoformat() could not handle the "Z" suffix
if value.upper().endswith("Z"):
Expand All @@ -30,33 +30,30 @@ def as_aware_datetime(value: Any) -> Any:
return value


def as_date(value: Any) -> Any:
def as_date(value: date | str) -> date:
if isinstance(value, str):
return date.fromisoformat(value)

return value


def as_timezone(value: Any) -> Any:
def as_timezone(value: tzinfo | str) -> tzinfo:
if isinstance(value, str):
if value is None or value == "local":
return get_localzone()

return ZoneInfo(value)
return get_localzone() if value == "local" else ZoneInfo(value)
elif value is timezone.utc:
return ZoneInfo("UTC")

return value


def as_uuid(value: Any) -> Any:
def as_uuid(value: UUID | str) -> UUID:
if isinstance(value, str):
return UUID(value)

return value


def as_timedelta(value: Any) -> Any:
def as_timedelta(value: timedelta | int) -> timedelta:
if isinstance(value, (float, int)):
return timedelta(seconds=value)

Expand All @@ -66,7 +63,7 @@ def as_timedelta(value: Any) -> Any:
def as_enum(enum_class: Any) -> Callable[[Any], Any]:
def converter(value: Any) -> Any:
if isinstance(value, str):
return enum_class.__members__[value]
return enum_class[value]

return value

Expand Down
2 changes: 1 addition & 1 deletion src/apscheduler/triggers/cron/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def from_crontab(
*,
start_time: datetime | None = None,
end_time: datetime | None = None,
timezone: str | tzinfo = "local",
timezone: tzinfo | str = "local",
) -> CronTrigger:
"""
Create a :class:`~CronTrigger` from a standard crontab expression.
Expand Down

0 comments on commit 8548e7f

Please sign in to comment.