1
0

number.py 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. """Immutable number vars."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import json
  5. import math
  6. from collections.abc import Callable
  7. from typing import TYPE_CHECKING, Any, NoReturn, TypeVar, overload
  8. from typing_extensions import TypeVar as TypeVarExt
  9. from reflex.constants.base import Dirs
  10. from reflex.utils.exceptions import (
  11. PrimitiveUnserializableToJSONError,
  12. VarTypeError,
  13. VarValueError,
  14. )
  15. from reflex.utils.imports import ImportDict, ImportVar
  16. from reflex.utils.types import safe_issubclass
  17. from .base import (
  18. CustomVarOperationReturn,
  19. LiteralVar,
  20. Var,
  21. VarData,
  22. unionize,
  23. var_operation,
  24. var_operation_return,
  25. )
  26. NUMBER_T = TypeVarExt(
  27. "NUMBER_T", bound=(int | float), default=(int | float), covariant=True
  28. )
  29. if TYPE_CHECKING:
  30. from .sequence import ArrayVar
  31. def raise_unsupported_operand_types(
  32. operator: str, operands_types: tuple[type, ...]
  33. ) -> NoReturn:
  34. """Raise an unsupported operand types error.
  35. Args:
  36. operator: The operator.
  37. operands_types: The types of the operands.
  38. Raises:
  39. VarTypeError: The operand types are unsupported.
  40. """
  41. raise VarTypeError(
  42. f"Unsupported Operand type(s) for {operator}: {', '.join(t.__name__ for t in operands_types)}"
  43. )
  44. class NumberVar(Var[NUMBER_T], python_types=(int, float)):
  45. """Base class for immutable number vars."""
  46. def __add__(self, other: number_types) -> NumberVar:
  47. """Add two numbers.
  48. Args:
  49. other: The other number.
  50. Returns:
  51. The number addition operation.
  52. """
  53. if not isinstance(other, NUMBER_TYPES):
  54. raise_unsupported_operand_types("+", (type(self), type(other)))
  55. return number_add_operation(self, +other)
  56. def __radd__(self, other: number_types) -> NumberVar:
  57. """Add two numbers.
  58. Args:
  59. other: The other number.
  60. Returns:
  61. The number addition operation.
  62. """
  63. if not isinstance(other, NUMBER_TYPES):
  64. raise_unsupported_operand_types("+", (type(other), type(self)))
  65. return number_add_operation(+other, self)
  66. def __sub__(self, other: number_types) -> NumberVar:
  67. """Subtract two numbers.
  68. Args:
  69. other: The other number.
  70. Returns:
  71. The number subtraction operation.
  72. """
  73. if not isinstance(other, NUMBER_TYPES):
  74. raise_unsupported_operand_types("-", (type(self), type(other)))
  75. return number_subtract_operation(self, +other)
  76. def __rsub__(self, other: number_types) -> NumberVar:
  77. """Subtract two numbers.
  78. Args:
  79. other: The other number.
  80. Returns:
  81. The number subtraction operation.
  82. """
  83. if not isinstance(other, NUMBER_TYPES):
  84. raise_unsupported_operand_types("-", (type(other), type(self)))
  85. return number_subtract_operation(+other, self)
  86. def __abs__(self):
  87. """Get the absolute value of the number.
  88. Returns:
  89. The number absolute operation.
  90. """
  91. return number_abs_operation(self)
  92. @overload
  93. def __mul__(self, other: number_types | boolean_types) -> NumberVar: ...
  94. @overload
  95. def __mul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
  96. def __mul__(self, other: Any):
  97. """Multiply two numbers.
  98. Args:
  99. other: The other number.
  100. Returns:
  101. The number multiplication operation.
  102. """
  103. from .sequence import ArrayVar, LiteralArrayVar
  104. if isinstance(other, (list, tuple, ArrayVar)):
  105. if isinstance(other, ArrayVar):
  106. return other * self
  107. return LiteralArrayVar.create(other) * self
  108. if not isinstance(other, NUMBER_TYPES):
  109. raise_unsupported_operand_types("*", (type(self), type(other)))
  110. return number_multiply_operation(self, +other)
  111. @overload
  112. def __rmul__(self, other: number_types | boolean_types) -> NumberVar: ...
  113. @overload
  114. def __rmul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
  115. def __rmul__(self, other: Any):
  116. """Multiply two numbers.
  117. Args:
  118. other: The other number.
  119. Returns:
  120. The number multiplication operation.
  121. """
  122. from .sequence import ArrayVar, LiteralArrayVar
  123. if isinstance(other, (list, tuple, ArrayVar)):
  124. if isinstance(other, ArrayVar):
  125. return other * self
  126. return LiteralArrayVar.create(other) * self
  127. if not isinstance(other, NUMBER_TYPES):
  128. raise_unsupported_operand_types("*", (type(other), type(self)))
  129. return number_multiply_operation(+other, self)
  130. def __truediv__(self, other: number_types) -> NumberVar:
  131. """Divide two numbers.
  132. Args:
  133. other: The other number.
  134. Returns:
  135. The number true division operation.
  136. """
  137. if not isinstance(other, NUMBER_TYPES):
  138. raise_unsupported_operand_types("/", (type(self), type(other)))
  139. return number_true_division_operation(self, +other)
  140. def __rtruediv__(self, other: number_types) -> NumberVar:
  141. """Divide two numbers.
  142. Args:
  143. other: The other number.
  144. Returns:
  145. The number true division operation.
  146. """
  147. if not isinstance(other, NUMBER_TYPES):
  148. raise_unsupported_operand_types("/", (type(other), type(self)))
  149. return number_true_division_operation(+other, self)
  150. def __floordiv__(self, other: number_types) -> NumberVar:
  151. """Floor divide two numbers.
  152. Args:
  153. other: The other number.
  154. Returns:
  155. The number floor division operation.
  156. """
  157. if not isinstance(other, NUMBER_TYPES):
  158. raise_unsupported_operand_types("//", (type(self), type(other)))
  159. return number_floor_division_operation(self, +other)
  160. def __rfloordiv__(self, other: number_types) -> NumberVar:
  161. """Floor divide two numbers.
  162. Args:
  163. other: The other number.
  164. Returns:
  165. The number floor division operation.
  166. """
  167. if not isinstance(other, NUMBER_TYPES):
  168. raise_unsupported_operand_types("//", (type(other), type(self)))
  169. return number_floor_division_operation(+other, self)
  170. def __mod__(self, other: number_types) -> NumberVar:
  171. """Modulo two numbers.
  172. Args:
  173. other: The other number.
  174. Returns:
  175. The number modulo operation.
  176. """
  177. if not isinstance(other, NUMBER_TYPES):
  178. raise_unsupported_operand_types("%", (type(self), type(other)))
  179. return number_modulo_operation(self, +other)
  180. def __rmod__(self, other: number_types) -> NumberVar:
  181. """Modulo two numbers.
  182. Args:
  183. other: The other number.
  184. Returns:
  185. The number modulo operation.
  186. """
  187. if not isinstance(other, NUMBER_TYPES):
  188. raise_unsupported_operand_types("%", (type(other), type(self)))
  189. return number_modulo_operation(+other, self)
  190. def __pow__(self, other: number_types) -> NumberVar:
  191. """Exponentiate two numbers.
  192. Args:
  193. other: The other number.
  194. Returns:
  195. The number exponent operation.
  196. """
  197. if not isinstance(other, NUMBER_TYPES):
  198. raise_unsupported_operand_types("**", (type(self), type(other)))
  199. return number_exponent_operation(self, +other)
  200. def __rpow__(self, other: number_types) -> NumberVar:
  201. """Exponentiate two numbers.
  202. Args:
  203. other: The other number.
  204. Returns:
  205. The number exponent operation.
  206. """
  207. if not isinstance(other, NUMBER_TYPES):
  208. raise_unsupported_operand_types("**", (type(other), type(self)))
  209. return number_exponent_operation(+other, self)
  210. def __neg__(self):
  211. """Negate the number.
  212. Returns:
  213. The number negation operation.
  214. """
  215. return number_negate_operation(self)
  216. def __invert__(self):
  217. """Boolean NOT the number.
  218. Returns:
  219. The boolean NOT operation.
  220. """
  221. return boolean_not_operation(self.bool())
  222. def __pos__(self) -> NumberVar:
  223. """Positive the number.
  224. Returns:
  225. The number.
  226. """
  227. return self
  228. def __round__(self, ndigits: int | NumberVar = 0) -> NumberVar:
  229. """Round the number.
  230. Args:
  231. ndigits: The number of digits to round.
  232. Returns:
  233. The number round operation.
  234. """
  235. if not isinstance(ndigits, NUMBER_TYPES):
  236. raise_unsupported_operand_types("round", (type(self), type(ndigits)))
  237. return number_round_operation(self, +ndigits)
  238. def __ceil__(self):
  239. """Ceil the number.
  240. Returns:
  241. The number ceil operation.
  242. """
  243. return number_ceil_operation(self)
  244. def __floor__(self):
  245. """Floor the number.
  246. Returns:
  247. The number floor operation.
  248. """
  249. return number_floor_operation(self)
  250. def __trunc__(self):
  251. """Trunc the number.
  252. Returns:
  253. The number trunc operation.
  254. """
  255. return number_trunc_operation(self)
  256. def __lt__(self, other: number_types) -> BooleanVar:
  257. """Less than comparison.
  258. Args:
  259. other: The other number.
  260. Returns:
  261. The result of the comparison.
  262. """
  263. if not isinstance(other, NUMBER_TYPES):
  264. raise_unsupported_operand_types("<", (type(self), type(other)))
  265. return less_than_operation(+self, +other)
  266. def __le__(self, other: number_types) -> BooleanVar:
  267. """Less than or equal comparison.
  268. Args:
  269. other: The other number.
  270. Returns:
  271. The result of the comparison.
  272. """
  273. if not isinstance(other, NUMBER_TYPES):
  274. raise_unsupported_operand_types("<=", (type(self), type(other)))
  275. return less_than_or_equal_operation(+self, +other)
  276. def __eq__(self, other: Any):
  277. """Equal comparison.
  278. Args:
  279. other: The other number.
  280. Returns:
  281. The result of the comparison.
  282. """
  283. if isinstance(other, NUMBER_TYPES):
  284. return equal_operation(+self, +other)
  285. return equal_operation(self, other)
  286. def __ne__(self, other: Any):
  287. """Not equal comparison.
  288. Args:
  289. other: The other number.
  290. Returns:
  291. The result of the comparison.
  292. """
  293. if isinstance(other, NUMBER_TYPES):
  294. return not_equal_operation(+self, +other)
  295. return not_equal_operation(self, other)
  296. def __gt__(self, other: number_types) -> BooleanVar:
  297. """Greater than comparison.
  298. Args:
  299. other: The other number.
  300. Returns:
  301. The result of the comparison.
  302. """
  303. if not isinstance(other, NUMBER_TYPES):
  304. raise_unsupported_operand_types(">", (type(self), type(other)))
  305. return greater_than_operation(+self, +other)
  306. def __ge__(self, other: number_types) -> BooleanVar:
  307. """Greater than or equal comparison.
  308. Args:
  309. other: The other number.
  310. Returns:
  311. The result of the comparison.
  312. """
  313. if not isinstance(other, NUMBER_TYPES):
  314. raise_unsupported_operand_types(">=", (type(self), type(other)))
  315. return greater_than_or_equal_operation(+self, +other)
  316. def _is_strict_float(self) -> bool:
  317. """Check if the number is a float.
  318. Returns:
  319. bool: True if the number is a float.
  320. """
  321. return safe_issubclass(self._var_type, float)
  322. def _is_strict_int(self) -> bool:
  323. """Check if the number is an int.
  324. Returns:
  325. bool: True if the number is an int.
  326. """
  327. return safe_issubclass(self._var_type, int)
  328. def __format__(self, format_spec: str) -> str:
  329. """Format the number.
  330. Args:
  331. format_spec: The format specifier.
  332. Returns:
  333. The formatted number.
  334. Raises:
  335. VarValueError: If the format specifier is not supported.
  336. """
  337. from .sequence import (
  338. get_decimal_string_operation,
  339. get_decimal_string_separator_operation,
  340. )
  341. separator = ""
  342. if format_spec and format_spec[:1] == ",":
  343. separator = ","
  344. format_spec = format_spec[1:]
  345. elif format_spec and format_spec[:1] == "_":
  346. separator = "_"
  347. format_spec = format_spec[1:]
  348. if (
  349. format_spec
  350. and format_spec[-1] == "f"
  351. and format_spec[0] == "."
  352. and format_spec[1:-1].isdigit()
  353. ):
  354. how_many_decimals = int(format_spec[1:-1])
  355. return f"{get_decimal_string_operation(self, Var.create(how_many_decimals), Var.create(separator))}"
  356. if not format_spec and separator:
  357. return (
  358. f"{get_decimal_string_separator_operation(self, Var.create(separator))}"
  359. )
  360. if format_spec:
  361. raise VarValueError(
  362. f"Unknown format code '{format_spec}' for object of type 'NumberVar'. It is only supported to use ',', '_', and '.f' for float numbers."
  363. "If possible, use computed variables instead: https://reflex.dev/docs/vars/computed-vars/"
  364. )
  365. return super().__format__(format_spec)
  366. def binary_number_operation(
  367. func: Callable[[NumberVar, NumberVar], str],
  368. ) -> Callable[[number_types, number_types], NumberVar]:
  369. """Decorator to create a binary number operation.
  370. Args:
  371. func: The binary number operation function.
  372. Returns:
  373. The binary number operation.
  374. """
  375. @var_operation
  376. def operation(lhs: NumberVar, rhs: NumberVar):
  377. return var_operation_return(
  378. js_expression=func(lhs, rhs),
  379. var_type=unionize(lhs._var_type, rhs._var_type),
  380. )
  381. def wrapper(lhs: number_types, rhs: number_types) -> NumberVar:
  382. """Create the binary number operation.
  383. Args:
  384. lhs: The first number.
  385. rhs: The second number.
  386. Returns:
  387. The binary number operation.
  388. """
  389. return operation(lhs, rhs) # pyright: ignore [reportReturnType, reportArgumentType]
  390. return wrapper
  391. @binary_number_operation
  392. def number_add_operation(lhs: NumberVar, rhs: NumberVar):
  393. """Add two numbers.
  394. Args:
  395. lhs: The first number.
  396. rhs: The second number.
  397. Returns:
  398. The number addition operation.
  399. """
  400. return f"({lhs} + {rhs})"
  401. @binary_number_operation
  402. def number_subtract_operation(lhs: NumberVar, rhs: NumberVar):
  403. """Subtract two numbers.
  404. Args:
  405. lhs: The first number.
  406. rhs: The second number.
  407. Returns:
  408. The number subtraction operation.
  409. """
  410. return f"({lhs} - {rhs})"
  411. @var_operation
  412. def number_abs_operation(value: NumberVar):
  413. """Get the absolute value of the number.
  414. Args:
  415. value: The number.
  416. Returns:
  417. The number absolute operation.
  418. """
  419. return var_operation_return(
  420. js_expression=f"Math.abs({value})", var_type=value._var_type
  421. )
  422. @binary_number_operation
  423. def number_multiply_operation(lhs: NumberVar, rhs: NumberVar):
  424. """Multiply two numbers.
  425. Args:
  426. lhs: The first number.
  427. rhs: The second number.
  428. Returns:
  429. The number multiplication operation.
  430. """
  431. return f"({lhs} * {rhs})"
  432. @var_operation
  433. def number_negate_operation(
  434. value: NumberVar[NUMBER_T],
  435. ) -> CustomVarOperationReturn[NUMBER_T]:
  436. """Negate the number.
  437. Args:
  438. value: The number.
  439. Returns:
  440. The number negation operation.
  441. """
  442. return var_operation_return(js_expression=f"-({value})", var_type=value._var_type)
  443. @binary_number_operation
  444. def number_true_division_operation(lhs: NumberVar, rhs: NumberVar):
  445. """Divide two numbers.
  446. Args:
  447. lhs: The first number.
  448. rhs: The second number.
  449. Returns:
  450. The number true division operation.
  451. """
  452. return f"({lhs} / {rhs})"
  453. @binary_number_operation
  454. def number_floor_division_operation(lhs: NumberVar, rhs: NumberVar):
  455. """Floor divide two numbers.
  456. Args:
  457. lhs: The first number.
  458. rhs: The second number.
  459. Returns:
  460. The number floor division operation.
  461. """
  462. return f"Math.floor({lhs} / {rhs})"
  463. @binary_number_operation
  464. def number_modulo_operation(lhs: NumberVar, rhs: NumberVar):
  465. """Modulo two numbers.
  466. Args:
  467. lhs: The first number.
  468. rhs: The second number.
  469. Returns:
  470. The number modulo operation.
  471. """
  472. return f"({lhs} % {rhs})"
  473. @binary_number_operation
  474. def number_exponent_operation(lhs: NumberVar, rhs: NumberVar):
  475. """Exponentiate two numbers.
  476. Args:
  477. lhs: The first number.
  478. rhs: The second number.
  479. Returns:
  480. The number exponent operation.
  481. """
  482. return f"({lhs} ** {rhs})"
  483. @var_operation
  484. def number_round_operation(value: NumberVar, ndigits: NumberVar | int):
  485. """Round the number.
  486. Args:
  487. value: The number.
  488. ndigits: The number of digits.
  489. Returns:
  490. The number round operation.
  491. """
  492. if (isinstance(ndigits, LiteralNumberVar) and ndigits._var_value == 0) or (
  493. isinstance(ndigits, int) and ndigits == 0
  494. ):
  495. return var_operation_return(js_expression=f"Math.round({value})", var_type=int)
  496. return var_operation_return(
  497. js_expression=f"(+{value}.toFixed({ndigits}))", var_type=float
  498. )
  499. @var_operation
  500. def number_ceil_operation(value: NumberVar):
  501. """Ceil the number.
  502. Args:
  503. value: The number.
  504. Returns:
  505. The number ceil operation.
  506. """
  507. return var_operation_return(js_expression=f"Math.ceil({value})", var_type=int)
  508. @var_operation
  509. def number_floor_operation(value: NumberVar):
  510. """Floor the number.
  511. Args:
  512. value: The number.
  513. Returns:
  514. The number floor operation.
  515. """
  516. return var_operation_return(js_expression=f"Math.floor({value})", var_type=int)
  517. @var_operation
  518. def number_trunc_operation(value: NumberVar):
  519. """Trunc the number.
  520. Args:
  521. value: The number.
  522. Returns:
  523. The number trunc operation.
  524. """
  525. return var_operation_return(js_expression=f"Math.trunc({value})", var_type=int)
  526. class BooleanVar(NumberVar[bool], python_types=bool):
  527. """Base class for immutable boolean vars."""
  528. def __invert__(self):
  529. """NOT the boolean.
  530. Returns:
  531. The boolean NOT operation.
  532. """
  533. return boolean_not_operation(self)
  534. def __int__(self):
  535. """Convert the boolean to an int.
  536. Returns:
  537. The boolean to int operation.
  538. """
  539. return boolean_to_number_operation(self)
  540. def __pos__(self):
  541. """Convert the boolean to an int.
  542. Returns:
  543. The boolean to int operation.
  544. """
  545. return boolean_to_number_operation(self)
  546. def bool(self) -> BooleanVar:
  547. """Boolean conversion.
  548. Returns:
  549. The boolean value of the boolean.
  550. """
  551. return self
  552. def __lt__(self, other: Any):
  553. """Less than comparison.
  554. Args:
  555. other: The other boolean.
  556. Returns:
  557. The result of the comparison.
  558. """
  559. return +self < other
  560. def __le__(self, other: Any):
  561. """Less than or equal comparison.
  562. Args:
  563. other: The other boolean.
  564. Returns:
  565. The result of the comparison.
  566. """
  567. return +self <= other
  568. def __gt__(self, other: Any):
  569. """Greater than comparison.
  570. Args:
  571. other: The other boolean.
  572. Returns:
  573. The result of the comparison.
  574. """
  575. return +self > other
  576. def __ge__(self, other: Any):
  577. """Greater than or equal comparison.
  578. Args:
  579. other: The other boolean.
  580. Returns:
  581. The result of the comparison.
  582. """
  583. return +self >= other
  584. @var_operation
  585. def boolean_to_number_operation(value: BooleanVar):
  586. """Convert the boolean to a number.
  587. Args:
  588. value: The boolean.
  589. Returns:
  590. The boolean to number operation.
  591. """
  592. return var_operation_return(js_expression=f"Number({value})", var_type=int)
  593. def comparison_operator(
  594. func: Callable[[Var, Var], str],
  595. ) -> Callable[[Var | Any, Var | Any], BooleanVar]:
  596. """Decorator to create a comparison operation.
  597. Args:
  598. func: The comparison operation function.
  599. Returns:
  600. The comparison operation.
  601. """
  602. @var_operation
  603. def operation(lhs: Var, rhs: Var):
  604. return var_operation_return(
  605. js_expression=func(lhs, rhs),
  606. var_type=bool,
  607. )
  608. def wrapper(lhs: Var | Any, rhs: Var | Any) -> BooleanVar:
  609. """Create the comparison operation.
  610. Args:
  611. lhs: The first value.
  612. rhs: The second value.
  613. Returns:
  614. The comparison operation.
  615. """
  616. return operation(lhs, rhs)
  617. return wrapper
  618. @comparison_operator
  619. def greater_than_operation(lhs: Var, rhs: Var):
  620. """Greater than comparison.
  621. Args:
  622. lhs: The first value.
  623. rhs: The second value.
  624. Returns:
  625. The result of the comparison.
  626. """
  627. return f"({lhs} > {rhs})"
  628. @comparison_operator
  629. def greater_than_or_equal_operation(lhs: Var, rhs: Var):
  630. """Greater than or equal comparison.
  631. Args:
  632. lhs: The first value.
  633. rhs: The second value.
  634. Returns:
  635. The result of the comparison.
  636. """
  637. return f"({lhs} >= {rhs})"
  638. @comparison_operator
  639. def less_than_operation(lhs: Var, rhs: Var):
  640. """Less than comparison.
  641. Args:
  642. lhs: The first value.
  643. rhs: The second value.
  644. Returns:
  645. The result of the comparison.
  646. """
  647. return f"({lhs} < {rhs})"
  648. @comparison_operator
  649. def less_than_or_equal_operation(lhs: Var, rhs: Var):
  650. """Less than or equal comparison.
  651. Args:
  652. lhs: The first value.
  653. rhs: The second value.
  654. Returns:
  655. The result of the comparison.
  656. """
  657. return f"({lhs} <= {rhs})"
  658. @comparison_operator
  659. def equal_operation(lhs: Var, rhs: Var):
  660. """Equal comparison.
  661. Args:
  662. lhs: The first value.
  663. rhs: The second value.
  664. Returns:
  665. The result of the comparison.
  666. """
  667. return f"({lhs} === {rhs})"
  668. @comparison_operator
  669. def not_equal_operation(lhs: Var, rhs: Var):
  670. """Not equal comparison.
  671. Args:
  672. lhs: The first value.
  673. rhs: The second value.
  674. Returns:
  675. The result of the comparison.
  676. """
  677. return f"({lhs} !== {rhs})"
  678. @var_operation
  679. def boolean_not_operation(value: BooleanVar):
  680. """Boolean NOT the boolean.
  681. Args:
  682. value: The boolean.
  683. Returns:
  684. The boolean NOT operation.
  685. """
  686. return var_operation_return(js_expression=f"!({value})", var_type=bool)
  687. @dataclasses.dataclass(
  688. eq=False,
  689. frozen=True,
  690. slots=True,
  691. )
  692. class LiteralNumberVar(LiteralVar, NumberVar[NUMBER_T]):
  693. """Base class for immutable literal number vars."""
  694. _var_value: float | int = dataclasses.field(default=0)
  695. def json(self) -> str:
  696. """Get the JSON representation of the var.
  697. Returns:
  698. The JSON representation of the var.
  699. Raises:
  700. PrimitiveUnserializableToJSONError: If the var is unserializable to JSON.
  701. """
  702. if math.isinf(self._var_value) or math.isnan(self._var_value):
  703. raise PrimitiveUnserializableToJSONError(
  704. f"No valid JSON representation for {self}"
  705. )
  706. return json.dumps(self._var_value)
  707. def __hash__(self) -> int:
  708. """Calculate the hash value of the object.
  709. Returns:
  710. int: The hash value of the object.
  711. """
  712. return hash((type(self).__name__, self._var_value))
  713. @classmethod
  714. def create(cls, value: float | int, _var_data: VarData | None = None):
  715. """Create the number var.
  716. Args:
  717. value: The value of the var.
  718. _var_data: Additional hooks and imports associated with the Var.
  719. Returns:
  720. The number var.
  721. """
  722. if math.isinf(value):
  723. js_expr = "Infinity" if value > 0 else "-Infinity"
  724. elif math.isnan(value):
  725. js_expr = "NaN"
  726. else:
  727. js_expr = str(value)
  728. return cls(
  729. _js_expr=js_expr,
  730. _var_type=type(value),
  731. _var_data=_var_data,
  732. _var_value=value,
  733. )
  734. @dataclasses.dataclass(
  735. eq=False,
  736. frozen=True,
  737. slots=True,
  738. )
  739. class LiteralBooleanVar(LiteralVar, BooleanVar):
  740. """Base class for immutable literal boolean vars."""
  741. _var_value: bool = dataclasses.field(default=False)
  742. def json(self) -> str:
  743. """Get the JSON representation of the var.
  744. Returns:
  745. The JSON representation of the var.
  746. """
  747. return "true" if self._var_value else "false"
  748. def __hash__(self) -> int:
  749. """Calculate the hash value of the object.
  750. Returns:
  751. int: The hash value of the object.
  752. """
  753. return hash((type(self).__name__, self._var_value))
  754. @classmethod
  755. def create(cls, value: bool, _var_data: VarData | None = None):
  756. """Create the boolean var.
  757. Args:
  758. value: The value of the var.
  759. _var_data: Additional hooks and imports associated with the Var.
  760. Returns:
  761. The boolean var.
  762. """
  763. return cls(
  764. _js_expr="true" if value else "false",
  765. _var_type=bool,
  766. _var_data=_var_data,
  767. _var_value=value,
  768. )
  769. number_types = NumberVar | int | float
  770. boolean_types = BooleanVar | bool
  771. _IS_TRUE_IMPORT: ImportDict = {
  772. f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
  773. }
  774. _IS_NOT_NULL_OR_UNDEFINED_IMPORT: ImportDict = {
  775. f"$/{Dirs.STATE_PATH}": [ImportVar(tag="isNotNullOrUndefined")],
  776. }
  777. @var_operation
  778. def boolify(value: Var):
  779. """Convert the value to a boolean.
  780. Args:
  781. value: The value.
  782. Returns:
  783. The boolean value.
  784. """
  785. return var_operation_return(
  786. js_expression=f"isTrue({value})",
  787. var_type=bool,
  788. var_data=VarData(imports=_IS_TRUE_IMPORT),
  789. )
  790. @var_operation
  791. def is_not_none_operation(value: Var):
  792. """Check if the value is not None.
  793. Args:
  794. value: The value.
  795. Returns:
  796. The boolean value.
  797. """
  798. return var_operation_return(
  799. js_expression=f"isNotNullOrUndefined({value})",
  800. var_type=bool,
  801. var_data=VarData(imports=_IS_NOT_NULL_OR_UNDEFINED_IMPORT),
  802. )
  803. T = TypeVar("T")
  804. U = TypeVar("U")
  805. @var_operation
  806. def ternary_operation(
  807. condition: Var[bool], if_true: Var[T], if_false: Var[U]
  808. ) -> CustomVarOperationReturn[T | U]:
  809. """Create a ternary operation.
  810. Args:
  811. condition: The condition.
  812. if_true: The value if the condition is true.
  813. if_false: The value if the condition is false.
  814. Returns:
  815. The ternary operation.
  816. """
  817. type_value: type[T] | type[U] = unionize(if_true._var_type, if_false._var_type)
  818. value: CustomVarOperationReturn[T | U] = var_operation_return(
  819. js_expression=f"({condition} ? {if_true} : {if_false})",
  820. var_type=type_value,
  821. )
  822. return value
  823. NUMBER_TYPES = (int, float, NumberVar)