number.py 27 KB

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