Skip to content
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

add datetime var comparison operations #4406

Merged
merged 7 commits into from
Dec 13, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 60 additions & 2 deletions reflex/vars/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,23 @@

from __future__ import annotations

import dataclasses
import json
import sys
from datetime import date, datetime
from typing import Any, NoReturn, TypeVar, Union, overload

from reflex.utils.exceptions import VarTypeError
from reflex.vars.number import BooleanVar

from .base import CustomVarOperationReturn, Var, var_operation, var_operation_return
from .base import (
CustomVarOperationReturn,
LiteralVar,
Var,
VarData,
var_operation,
var_operation_return,
)

DATETIME_T = TypeVar("DATETIME_T", datetime, date)

Expand Down Expand Up @@ -176,9 +186,57 @@ def date_compare_operation(
The result of the operation.
"""
return var_operation_return(
f"isTrue({lhs} { '<' if strict else '<='} {rhs})",
f"({lhs} { '<' if strict else '<='} {rhs})",
bool,
)


@dataclasses.dataclass(
eq=False,
frozen=True,
**{"slots": True} if sys.version_info >= (3, 10) else {},
)
class LiteralDatetimeVar(LiteralVar, DateTimeVar):
"""Base class for immutable datetime and date vars."""

_var_value: datetime | date = dataclasses.field(default=datetime.now())

def json(self) -> str:
"""Return the JSON representation of the datetime.

Returns:
The JSON representation of the datetime.
"""
return json.dumps(self._var_value)
Lendemor marked this conversation as resolved.
Show resolved Hide resolved

def __hash__(self) -> int:
"""Calculate the hash value of the object.

Returns:
int: The hash value of the object.
"""
return hash((self.__class__.__name__, self._var_value))
Lendemor marked this conversation as resolved.
Show resolved Hide resolved

@classmethod
def create(cls, value: datetime | date, _var_data: VarData | None = None):
"""Create a new instance of the class.

Args:
value: The value to set.

Returns:
LiteralDatetimeVar: The new instance of the class.
"""
if isinstance(value, datetime):
js_expr = f"new Date({value.year}, {value.month - 1}, {value.day}, {value.hour}, {value.minute}, {value.second}, {value.microsecond})"
elif isinstance(value, date):
js_expr = f"new Date({value.year}, {value.month - 1}, {value.day})"
return cls(
_js_expr=js_expr,
_var_type=type(value),
_var_value=value,
_var_data=_var_data,
)


DATETIME_TYPES = (datetime, date, DateTimeVar)
Loading