number.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. ClassVar,
  12. NoReturn,
  13. Type,
  14. TypeVar,
  15. Union,
  16. overload,
  17. )
  18. from reflex.constants.base import Dirs
  19. from reflex.utils.exceptions import PrimitiveUnserializableToJSON, VarTypeError
  20. from reflex.utils.imports import ImportDict, ImportVar
  21. from .base import (
  22. CustomVarOperationReturn,
  23. LiteralNoneVar,
  24. LiteralVar,
  25. ToOperation,
  26. Var,
  27. VarData,
  28. unionize,
  29. var_operation,
  30. var_operation_return,
  31. )
  32. NUMBER_T = TypeVar("NUMBER_T", int, float, Union[int, float], bool)
  33. if TYPE_CHECKING:
  34. from .sequence import ArrayVar
  35. def raise_unsupported_operand_types(
  36. operator: str, operands_types: tuple[type, ...]
  37. ) -> NoReturn:
  38. """Raise an unsupported operand types error.
  39. Args:
  40. operator: The operator.
  41. operands_types: The types of the operands.
  42. Raises:
  43. VarTypeError: The operand types are unsupported.
  44. """
  45. raise VarTypeError(
  46. f"Unsupported Operand type(s) for {operator}: {', '.join(map(lambda t: t.__name__, operands_types))}"
  47. )
  48. class NumberVar(Var[NUMBER_T]):
  49. """Base class for immutable number vars."""
  50. @overload
  51. def __add__(self, other: number_types) -> NumberVar: ...
  52. @overload
  53. def __add__(self, other: NoReturn) -> NoReturn: ...
  54. def __add__(self, other: Any):
  55. """Add two numbers.
  56. Args:
  57. other: The other number.
  58. Returns:
  59. The number addition operation.
  60. """
  61. if not isinstance(other, NUMBER_TYPES):
  62. raise_unsupported_operand_types("+", (type(self), type(other)))
  63. return number_add_operation(self, +other)
  64. @overload
  65. def __radd__(self, other: number_types) -> NumberVar: ...
  66. @overload
  67. def __radd__(self, other: NoReturn) -> NoReturn: ...
  68. def __radd__(self, other: Any):
  69. """Add two numbers.
  70. Args:
  71. other: The other number.
  72. Returns:
  73. The number addition operation.
  74. """
  75. if not isinstance(other, NUMBER_TYPES):
  76. raise_unsupported_operand_types("+", (type(other), type(self)))
  77. return number_add_operation(+other, self)
  78. @overload
  79. def __sub__(self, other: number_types) -> NumberVar: ...
  80. @overload
  81. def __sub__(self, other: NoReturn) -> NoReturn: ...
  82. def __sub__(self, other: Any):
  83. """Subtract two numbers.
  84. Args:
  85. other: The other number.
  86. Returns:
  87. The number subtraction operation.
  88. """
  89. if not isinstance(other, NUMBER_TYPES):
  90. raise_unsupported_operand_types("-", (type(self), type(other)))
  91. return number_subtract_operation(self, +other)
  92. @overload
  93. def __rsub__(self, other: number_types) -> NumberVar: ...
  94. @overload
  95. def __rsub__(self, other: NoReturn) -> NoReturn: ...
  96. def __rsub__(self, other: Any):
  97. """Subtract two numbers.
  98. Args:
  99. other: The other number.
  100. Returns:
  101. The number subtraction operation.
  102. """
  103. if not isinstance(other, NUMBER_TYPES):
  104. raise_unsupported_operand_types("-", (type(other), type(self)))
  105. return number_subtract_operation(+other, self)
  106. def __abs__(self):
  107. """Get the absolute value of the number.
  108. Returns:
  109. The number absolute operation.
  110. """
  111. return number_abs_operation(self)
  112. @overload
  113. def __mul__(self, other: number_types | boolean_types) -> NumberVar: ...
  114. @overload
  115. def __mul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
  116. def __mul__(self, other: Any):
  117. """Multiply two numbers.
  118. Args:
  119. other: The other number.
  120. Returns:
  121. The number multiplication operation.
  122. """
  123. from .sequence import ArrayVar, LiteralArrayVar
  124. if isinstance(other, (list, tuple, set, ArrayVar)):
  125. if isinstance(other, ArrayVar):
  126. return other * self
  127. return LiteralArrayVar.create(other) * self
  128. if not isinstance(other, NUMBER_TYPES):
  129. raise_unsupported_operand_types("*", (type(self), type(other)))
  130. return number_multiply_operation(self, +other)
  131. @overload
  132. def __rmul__(self, other: number_types | boolean_types) -> NumberVar: ...
  133. @overload
  134. def __rmul__(self, other: list | tuple | set | ArrayVar) -> ArrayVar: ...
  135. def __rmul__(self, other: Any):
  136. """Multiply two numbers.
  137. Args:
  138. other: The other number.
  139. Returns:
  140. The number multiplication operation.
  141. """
  142. from .sequence import ArrayVar, LiteralArrayVar
  143. if isinstance(other, (list, tuple, set, ArrayVar)):
  144. if isinstance(other, ArrayVar):
  145. return other * self
  146. return LiteralArrayVar.create(other) * self
  147. if not isinstance(other, NUMBER_TYPES):
  148. raise_unsupported_operand_types("*", (type(other), type(self)))
  149. return number_multiply_operation(+other, self)
  150. @overload
  151. def __truediv__(self, other: number_types) -> NumberVar: ...
  152. @overload
  153. def __truediv__(self, other: NoReturn) -> NoReturn: ...
  154. def __truediv__(self, other: Any):
  155. """Divide two numbers.
  156. Args:
  157. other: The other number.
  158. Returns:
  159. The number true division operation.
  160. """
  161. if not isinstance(other, NUMBER_TYPES):
  162. raise_unsupported_operand_types("/", (type(self), type(other)))
  163. return number_true_division_operation(self, +other)
  164. @overload
  165. def __rtruediv__(self, other: number_types) -> NumberVar: ...
  166. @overload
  167. def __rtruediv__(self, other: NoReturn) -> NoReturn: ...
  168. def __rtruediv__(self, other: Any):
  169. """Divide two numbers.
  170. Args:
  171. other: The other number.
  172. Returns:
  173. The number true division operation.
  174. """
  175. if not isinstance(other, NUMBER_TYPES):
  176. raise_unsupported_operand_types("/", (type(other), type(self)))
  177. return number_true_division_operation(+other, self)
  178. @overload
  179. def __floordiv__(self, other: number_types) -> NumberVar: ...
  180. @overload
  181. def __floordiv__(self, other: NoReturn) -> NoReturn: ...
  182. def __floordiv__(self, other: Any):
  183. """Floor divide two numbers.
  184. Args:
  185. other: The other number.
  186. Returns:
  187. The number floor division operation.
  188. """
  189. if not isinstance(other, NUMBER_TYPES):
  190. raise_unsupported_operand_types("//", (type(self), type(other)))
  191. return number_floor_division_operation(self, +other)
  192. @overload
  193. def __rfloordiv__(self, other: number_types) -> NumberVar: ...
  194. @overload
  195. def __rfloordiv__(self, other: NoReturn) -> NoReturn: ...
  196. def __rfloordiv__(self, other: Any):
  197. """Floor divide two numbers.
  198. Args:
  199. other: The other number.
  200. Returns:
  201. The number floor division operation.
  202. """
  203. if not isinstance(other, NUMBER_TYPES):
  204. raise_unsupported_operand_types("//", (type(other), type(self)))
  205. return number_floor_division_operation(+other, self)
  206. @overload
  207. def __mod__(self, other: number_types) -> NumberVar: ...
  208. @overload
  209. def __mod__(self, other: NoReturn) -> NoReturn: ...
  210. def __mod__(self, other: Any):
  211. """Modulo two numbers.
  212. Args:
  213. other: The other number.
  214. Returns:
  215. The number modulo operation.
  216. """
  217. if not isinstance(other, NUMBER_TYPES):
  218. raise_unsupported_operand_types("%", (type(self), type(other)))
  219. return number_modulo_operation(self, +other)
  220. @overload
  221. def __rmod__(self, other: number_types) -> NumberVar: ...
  222. @overload
  223. def __rmod__(self, other: NoReturn) -> NoReturn: ...
  224. def __rmod__(self, other: Any):
  225. """Modulo two numbers.
  226. Args:
  227. other: The other number.
  228. Returns:
  229. The number modulo operation.
  230. """
  231. if not isinstance(other, NUMBER_TYPES):
  232. raise_unsupported_operand_types("%", (type(other), type(self)))
  233. return number_modulo_operation(+other, self)
  234. @overload
  235. def __pow__(self, other: number_types) -> NumberVar: ...
  236. @overload
  237. def __pow__(self, other: NoReturn) -> NoReturn: ...
  238. def __pow__(self, other: Any):
  239. """Exponentiate two numbers.
  240. Args:
  241. other: The other number.
  242. Returns:
  243. The number exponent operation.
  244. """
  245. if not isinstance(other, NUMBER_TYPES):
  246. raise_unsupported_operand_types("**", (type(self), type(other)))
  247. return number_exponent_operation(self, +other)
  248. @overload
  249. def __rpow__(self, other: number_types) -> NumberVar: ...
  250. @overload
  251. def __rpow__(self, other: NoReturn) -> NoReturn: ...
  252. def __rpow__(self, other: Any):
  253. """Exponentiate two numbers.
  254. Args:
  255. other: The other number.
  256. Returns:
  257. The number exponent operation.
  258. """
  259. if not isinstance(other, NUMBER_TYPES):
  260. raise_unsupported_operand_types("**", (type(other), type(self)))
  261. return number_exponent_operation(+other, self)
  262. def __neg__(self):
  263. """Negate the number.
  264. Returns:
  265. The number negation operation.
  266. """
  267. return number_negate_operation(self)
  268. def __invert__(self):
  269. """Boolean NOT the number.
  270. Returns:
  271. The boolean NOT operation.
  272. """
  273. return boolean_not_operation(self.bool())
  274. def __pos__(self) -> NumberVar:
  275. """Positive the number.
  276. Returns:
  277. The number.
  278. """
  279. return self
  280. def __round__(self):
  281. """Round the number.
  282. Returns:
  283. The number round operation.
  284. """
  285. return number_round_operation(self)
  286. def __ceil__(self):
  287. """Ceil the number.
  288. Returns:
  289. The number ceil operation.
  290. """
  291. return number_ceil_operation(self)
  292. def __floor__(self):
  293. """Floor the number.
  294. Returns:
  295. The number floor operation.
  296. """
  297. return number_floor_operation(self)
  298. def __trunc__(self):
  299. """Trunc the number.
  300. Returns:
  301. The number trunc operation.
  302. """
  303. return number_trunc_operation(self)
  304. @overload
  305. def __lt__(self, other: number_types) -> BooleanVar: ...
  306. @overload
  307. def __lt__(self, other: NoReturn) -> NoReturn: ...
  308. def __lt__(self, other: Any):
  309. """Less than comparison.
  310. Args:
  311. other: The other number.
  312. Returns:
  313. The result of the comparison.
  314. """
  315. if not isinstance(other, NUMBER_TYPES):
  316. raise_unsupported_operand_types("<", (type(self), type(other)))
  317. return less_than_operation(self, +other)
  318. @overload
  319. def __le__(self, other: number_types) -> BooleanVar: ...
  320. @overload
  321. def __le__(self, other: NoReturn) -> NoReturn: ...
  322. def __le__(self, other: Any):
  323. """Less than or equal comparison.
  324. Args:
  325. other: The other number.
  326. Returns:
  327. The result of the comparison.
  328. """
  329. if not isinstance(other, NUMBER_TYPES):
  330. raise_unsupported_operand_types("<=", (type(self), type(other)))
  331. return less_than_or_equal_operation(self, +other)
  332. def __eq__(self, other: Any):
  333. """Equal comparison.
  334. Args:
  335. other: The other number.
  336. Returns:
  337. The result of the comparison.
  338. """
  339. if isinstance(other, NUMBER_TYPES):
  340. return equal_operation(self, +other)
  341. return equal_operation(self, other)
  342. def __ne__(self, other: Any):
  343. """Not equal comparison.
  344. Args:
  345. other: The other number.
  346. Returns:
  347. The result of the comparison.
  348. """
  349. if isinstance(other, NUMBER_TYPES):
  350. return not_equal_operation(self, +other)
  351. return not_equal_operation(self, other)
  352. @overload
  353. def __gt__(self, other: number_types) -> BooleanVar: ...
  354. @overload
  355. def __gt__(self, other: NoReturn) -> NoReturn: ...
  356. def __gt__(self, other: Any):
  357. """Greater than comparison.
  358. Args:
  359. other: The other number.
  360. Returns:
  361. The result of the comparison.
  362. """
  363. if not isinstance(other, NUMBER_TYPES):
  364. raise_unsupported_operand_types(">", (type(self), type(other)))
  365. return greater_than_operation(self, +other)
  366. @overload
  367. def __ge__(self, other: number_types) -> BooleanVar: ...
  368. @overload
  369. def __ge__(self, other: NoReturn) -> NoReturn: ...
  370. def __ge__(self, other: Any):
  371. """Greater than or equal comparison.
  372. Args:
  373. other: The other number.
  374. Returns:
  375. The result of the comparison.
  376. """
  377. if not isinstance(other, NUMBER_TYPES):
  378. raise_unsupported_operand_types(">=", (type(self), type(other)))
  379. return greater_than_or_equal_operation(self, +other)
  380. def bool(self):
  381. """Boolean conversion.
  382. Returns:
  383. The boolean value of the number.
  384. """
  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]):
  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 LiteralBooleanVar(LiteralVar, BooleanVar):
  718. """Base class for immutable literal boolean vars."""
  719. _var_value: bool = dataclasses.field(default=False)
  720. def json(self) -> str:
  721. """Get the JSON representation of the var.
  722. Returns:
  723. The JSON representation of the var.
  724. """
  725. return "true" if self._var_value else "false"
  726. def __hash__(self) -> int:
  727. """Calculate the hash value of the object.
  728. Returns:
  729. int: The hash value of the object.
  730. """
  731. return hash((self.__class__.__name__, self._var_value))
  732. @classmethod
  733. def create(cls, value: bool, _var_data: VarData | None = None):
  734. """Create the boolean var.
  735. Args:
  736. value: The value of the var.
  737. _var_data: Additional hooks and imports associated with the Var.
  738. Returns:
  739. The boolean var.
  740. """
  741. return cls(
  742. _js_expr="true" if value else "false",
  743. _var_type=bool,
  744. _var_data=_var_data,
  745. _var_value=value,
  746. )
  747. @dataclasses.dataclass(
  748. eq=False,
  749. frozen=True,
  750. **{"slots": True} if sys.version_info >= (3, 10) else {},
  751. )
  752. class LiteralNumberVar(LiteralVar, NumberVar):
  753. """Base class for immutable literal number vars."""
  754. _var_value: float | int = dataclasses.field(default=0)
  755. def json(self) -> str:
  756. """Get the JSON representation of the var.
  757. Returns:
  758. The JSON representation of the var.
  759. Raises:
  760. PrimitiveUnserializableToJSON: If the var is unserializable to JSON.
  761. """
  762. if math.isinf(self._var_value) or math.isnan(self._var_value):
  763. raise PrimitiveUnserializableToJSON(
  764. f"No valid JSON representation for {self}"
  765. )
  766. return json.dumps(self._var_value)
  767. def __hash__(self) -> int:
  768. """Calculate the hash value of the object.
  769. Returns:
  770. int: The hash value of the object.
  771. """
  772. return hash((self.__class__.__name__, self._var_value))
  773. @classmethod
  774. def create(cls, value: float | int, _var_data: VarData | None = None):
  775. """Create the number var.
  776. Args:
  777. value: The value of the var.
  778. _var_data: Additional hooks and imports associated with the Var.
  779. Returns:
  780. The number var.
  781. """
  782. if math.isinf(value):
  783. js_expr = "Infinity" if value > 0 else "-Infinity"
  784. elif math.isnan(value):
  785. js_expr = "NaN"
  786. else:
  787. js_expr = str(value)
  788. return cls(
  789. _js_expr=js_expr,
  790. _var_type=type(value),
  791. _var_data=_var_data,
  792. _var_value=value,
  793. )
  794. number_types = Union[NumberVar, int, float]
  795. boolean_types = Union[BooleanVar, bool]
  796. @dataclasses.dataclass(
  797. eq=False,
  798. frozen=True,
  799. **{"slots": True} if sys.version_info >= (3, 10) else {},
  800. )
  801. class ToNumberVarOperation(ToOperation, NumberVar):
  802. """Base class for immutable number vars that are the result of a number operation."""
  803. _original: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  804. _default_var_type: ClassVar[Type] = float
  805. @dataclasses.dataclass(
  806. eq=False,
  807. frozen=True,
  808. **{"slots": True} if sys.version_info >= (3, 10) else {},
  809. )
  810. class ToBooleanVarOperation(ToOperation, BooleanVar):
  811. """Base class for immutable boolean vars that are the result of a boolean operation."""
  812. _original: Var = dataclasses.field(default_factory=lambda: LiteralNoneVar.create())
  813. _default_var_type: ClassVar[Type] = bool
  814. _IS_TRUE_IMPORT: ImportDict = {
  815. f"/{Dirs.STATE_PATH}": [ImportVar(tag="isTrue")],
  816. }
  817. @var_operation
  818. def boolify(value: Var):
  819. """Convert the value to a boolean.
  820. Args:
  821. value: The value.
  822. Returns:
  823. The boolean value.
  824. """
  825. return var_operation_return(
  826. js_expression=f"isTrue({value})",
  827. var_type=bool,
  828. var_data=VarData(imports=_IS_TRUE_IMPORT),
  829. )
  830. @var_operation
  831. def ternary_operation(condition: BooleanVar, if_true: Var, if_false: Var):
  832. """Create a ternary operation.
  833. Args:
  834. condition: The condition.
  835. if_true: The value if the condition is true.
  836. if_false: The value if the condition is false.
  837. Returns:
  838. The ternary operation.
  839. """
  840. return var_operation_return(
  841. js_expression=f"({condition} ? {if_true} : {if_false})",
  842. var_type=unionize(if_true._var_type, if_false._var_type),
  843. )
  844. NUMBER_TYPES = (int, float, NumberVar)