blob: 9e299ddc4cf7a80c8a21f0038cdcd198c03dab82 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
from __future__ import annotations
from collections.abc import Callable
from datetime import datetime, timedelta
from enum import Enum
from typing import TypeVar
from uuid import UUID
TEnum = TypeVar("TEnum", bound=Enum)
def as_aware_datetime(value: datetime | str) -> datetime:
"""Convert the value from a string to a timezone aware datetime."""
if isinstance(value, str):
# fromisoformat() does not handle the "Z" suffix
if value.upper().endswith("Z"):
value = value[:-1] + "+00:00"
value = datetime.fromisoformat(value)
return value
def as_uuid(value: UUID | str) -> UUID:
"""Convert a string-formatted UUID to a UUID instance."""
if isinstance(value, str):
return UUID(value)
return value
def as_timedelta(value: timedelta | float | None) -> timedelta | None:
if isinstance(value, (float, int)):
return timedelta(seconds=value)
return value
def as_enum(enum_class: type[TEnum]) -> Callable[[TEnum | str], TEnum]:
def converter(value: TEnum | str) -> TEnum:
if isinstance(value, str):
return enum_class.__members__[value]
return value
return converter
|