datetime.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """Immutable datetime and date vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. from datetime import date, datetime
  5. from typing import Any, TypeVar
  6. from reflex.utils.exceptions import VarTypeError
  7. from reflex.vars.number import BooleanVar
  8. from .base import (
  9. CustomVarOperationReturn,
  10. LiteralVar,
  11. Var,
  12. VarData,
  13. var_operation,
  14. var_operation_return,
  15. )
  16. DATETIME_T = TypeVar("DATETIME_T", datetime, date)
  17. datetime_types = datetime | date
  18. def raise_var_type_error():
  19. """Raise a VarTypeError.
  20. Raises:
  21. VarTypeError: Cannot compare a datetime object with a non-datetime object.
  22. """
  23. raise VarTypeError("Cannot compare a datetime object with a non-datetime object.")
  24. class DateTimeVar(Var[DATETIME_T], python_types=(datetime, date)):
  25. """A variable that holds a datetime or date object."""
  26. def __lt__(self, other: datetime_types | DateTimeVar) -> BooleanVar:
  27. """Less than comparison.
  28. Args:
  29. other: The other datetime to compare.
  30. Returns:
  31. The result of the comparison.
  32. """
  33. if not isinstance(other, DATETIME_TYPES):
  34. raise_var_type_error()
  35. return date_lt_operation(self, other)
  36. def __le__(self, other: datetime_types | DateTimeVar) -> BooleanVar:
  37. """Less than or equal comparison.
  38. Args:
  39. other: The other datetime to compare.
  40. Returns:
  41. The result of the comparison.
  42. """
  43. if not isinstance(other, DATETIME_TYPES):
  44. raise_var_type_error()
  45. return date_le_operation(self, other)
  46. def __gt__(self, other: datetime_types | DateTimeVar) -> BooleanVar:
  47. """Greater than comparison.
  48. Args:
  49. other: The other datetime to compare.
  50. Returns:
  51. The result of the comparison.
  52. """
  53. if not isinstance(other, DATETIME_TYPES):
  54. raise_var_type_error()
  55. return date_gt_operation(self, other)
  56. def __ge__(self, other: datetime_types | DateTimeVar) -> BooleanVar:
  57. """Greater than or equal comparison.
  58. Args:
  59. other: The other datetime to compare.
  60. Returns:
  61. The result of the comparison.
  62. """
  63. if not isinstance(other, DATETIME_TYPES):
  64. raise_var_type_error()
  65. return date_ge_operation(self, other)
  66. @var_operation
  67. def date_gt_operation(lhs: DateTimeVar | Any, rhs: DateTimeVar | Any):
  68. """Greater than comparison.
  69. Args:
  70. lhs: The left-hand side of the operation.
  71. rhs: The right-hand side of the operation.
  72. Returns:
  73. The result of the operation.
  74. """
  75. return date_compare_operation(rhs, lhs, strict=True)
  76. @var_operation
  77. def date_lt_operation(lhs: DateTimeVar | Any, rhs: DateTimeVar | Any):
  78. """Less than comparison.
  79. Args:
  80. lhs: The left-hand side of the operation.
  81. rhs: The right-hand side of the operation.
  82. Returns:
  83. The result of the operation.
  84. """
  85. return date_compare_operation(lhs, rhs, strict=True)
  86. @var_operation
  87. def date_le_operation(lhs: DateTimeVar | Any, rhs: DateTimeVar | Any):
  88. """Less than or equal comparison.
  89. Args:
  90. lhs: The left-hand side of the operation.
  91. rhs: The right-hand side of the operation.
  92. Returns:
  93. The result of the operation.
  94. """
  95. return date_compare_operation(lhs, rhs)
  96. @var_operation
  97. def date_ge_operation(lhs: DateTimeVar | Any, rhs: DateTimeVar | Any):
  98. """Greater than or equal comparison.
  99. Args:
  100. lhs: The left-hand side of the operation.
  101. rhs: The right-hand side of the operation.
  102. Returns:
  103. The result of the operation.
  104. """
  105. return date_compare_operation(rhs, lhs)
  106. def date_compare_operation(
  107. lhs: DateTimeVar[DATETIME_T] | Any,
  108. rhs: DateTimeVar[DATETIME_T] | Any,
  109. strict: bool = False,
  110. ) -> CustomVarOperationReturn[bool]:
  111. """Check if the value is less than the other value.
  112. Args:
  113. lhs: The left-hand side of the operation.
  114. rhs: The right-hand side of the operation.
  115. strict: Whether to use strict comparison.
  116. Returns:
  117. The result of the operation.
  118. """
  119. return var_operation_return(
  120. f"({lhs} {'<' if strict else '<='} {rhs})",
  121. bool,
  122. )
  123. @dataclasses.dataclass(
  124. eq=False,
  125. frozen=True,
  126. slots=True,
  127. )
  128. class LiteralDatetimeVar(LiteralVar, DateTimeVar):
  129. """Base class for immutable datetime and date vars."""
  130. _var_value: datetime | date = dataclasses.field(default=datetime.now())
  131. @classmethod
  132. def create(cls, value: datetime | date, _var_data: VarData | None = None):
  133. """Create a new instance of the class.
  134. Args:
  135. value: The value to set.
  136. Returns:
  137. LiteralDatetimeVar: The new instance of the class.
  138. """
  139. js_expr = f'"{value!s}"'
  140. return cls(
  141. _js_expr=js_expr,
  142. _var_type=type(value),
  143. _var_value=value,
  144. _var_data=_var_data,
  145. )
  146. DATETIME_TYPES = (datetime, date, DateTimeVar)