forked from reflex-dev/reflex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvars.py
1966 lines (1619 loc) · 61.2 KB
/
vars.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Define a state var."""
from __future__ import annotations
import contextlib
import dataclasses
import dis
import inspect
import json
import random
import re
import string
import sys
from types import CodeType, FunctionType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Optional,
Set,
Tuple,
Type,
Union,
_GenericAlias, # type: ignore
cast,
get_args,
get_origin,
get_type_hints,
)
import pydantic
from reflex import constants
from reflex.base import Base
from reflex.utils import console, format, imports, serializers, types
# This module used to export ImportVar itself, so we still import it for export here
from reflex.utils.imports import ImportDict, ImportVar
if TYPE_CHECKING:
from reflex.state import BaseState
# Set of unique variable names.
USED_VARIABLES = set()
# Supported operators for all types.
ALL_OPS = ["==", "!=", "!==", "===", "&&", "||"]
# Delimiters used between function args or operands.
DELIMITERS = [","]
# Mapping of valid operations for different type combinations.
OPERATION_MAPPING = {
(int, int): {
"+",
"-",
"/",
"//",
"*",
"%",
"**",
">",
"<",
"<=",
">=",
"|",
"&",
},
(int, str): {"*"},
(int, list): {"*"},
(str, str): {"+", ">", "<", "<=", ">="},
(float, float): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
(float, int): {"+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="},
(list, list): {"+", ">", "<", "<=", ">="},
}
# These names were changed in reflex 0.3.0
REPLACED_NAMES = {
"full_name": "_var_full_name",
"name": "_var_name",
"state": "_var_data.state",
"type_": "_var_type",
"is_local": "_var_is_local",
"is_string": "_var_is_string",
"set_state": "_var_set_state",
"deps": "_deps",
}
PYTHON_JS_TYPE_MAP = {
(int, float): "number",
(str,): "string",
(bool,): "boolean",
(list, tuple): "Array",
(dict,): "Object",
(None,): "null",
}
def get_unique_variable_name() -> str:
"""Get a unique variable name.
Returns:
The unique variable name.
"""
name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
if name not in USED_VARIABLES:
USED_VARIABLES.add(name)
return name
return get_unique_variable_name()
class VarData(Base):
"""Metadata associated with a Var."""
# The name of the enclosing state.
state: str = ""
# Imports needed to render this var
imports: ImportDict = {}
# Hooks that need to be present in the component to render this var
hooks: Set[str] = set()
@classmethod
def merge(cls, *others: VarData | None) -> VarData | None:
"""Merge multiple var data objects.
Args:
*others: The var data objects to merge.
Returns:
The merged var data object.
"""
state = ""
_imports = {}
hooks = set()
for var_data in others:
if var_data is None:
continue
state = state or var_data.state
_imports = imports.merge_imports(_imports, var_data.imports)
hooks.update(var_data.hooks)
return (
cls(
state=state,
imports=_imports,
hooks=hooks,
)
or None
)
def __bool__(self) -> bool:
"""Check if the var data is non-empty.
Returns:
True if any field is set to a non-default value.
"""
return bool(self.state or self.imports or self.hooks)
def __eq__(self, other: Any) -> bool:
"""Check if two var data objects are equal.
Args:
other: The other var data object to compare.
Returns:
True if all fields are equal and collapsed imports are equal.
"""
if not isinstance(other, VarData):
return False
return (
self.state == other.state
and self.hooks == other.hooks
and imports.collapse_imports(self.imports)
== imports.collapse_imports(other.imports)
)
def dict(self) -> dict:
"""Convert the var data to a dictionary.
Returns:
The var data dictionary.
"""
return {
"state": self.state,
"imports": {
lib: [import_var.dict() for import_var in import_vars]
for lib, import_vars in self.imports.items()
},
"hooks": list(self.hooks),
}
def _encode_var(value: Var) -> str:
"""Encode the state name into a formatted var.
Args:
value: The value to encode the state name into.
Returns:
The encoded var.
"""
if value._var_data:
return (
f"{constants.REFLEX_VAR_OPENING_TAG}{value._var_data.json()}{constants.REFLEX_VAR_CLOSING_TAG}"
+ str(value)
)
return str(value)
def _decode_var(value: str) -> tuple[VarData | None, str]:
"""Decode the state name from a formatted var.
Args:
value: The value to extract the state name from.
Returns:
The extracted state name and the value without the state name.
"""
var_datas = []
if isinstance(value, str):
# Extract the state name from a formatted var
while m := re.match(
pattern=rf"(.*){constants.REFLEX_VAR_OPENING_TAG}(.*){constants.REFLEX_VAR_CLOSING_TAG}(.*)",
string=value,
flags=re.DOTALL, # Ensure . matches newline characters.
):
value = m.group(1) + m.group(3)
try:
var_datas.append(VarData.parse_raw(m.group(2)))
except pydantic.ValidationError:
# If the VarData is invalid, it was probably json-encoded twice...
var_datas.append(VarData.parse_raw(json.loads(f'"{m.group(2)}"')))
if var_datas:
return VarData.merge(*var_datas), value
return None, value
def _extract_var_data(value: Iterable) -> list[VarData | None]:
"""Extract the var imports and hooks from an iterable containing a Var.
Args:
value: The iterable to extract the VarData from
Returns:
The extracted VarDatas.
"""
from reflex.style import Style
var_datas = []
with contextlib.suppress(TypeError):
for sub in value:
if isinstance(sub, Var):
var_datas.append(sub._var_data)
elif not isinstance(sub, str):
# Recurse into dict values.
if hasattr(sub, "values") and callable(sub.values):
var_datas.extend(_extract_var_data(sub.values()))
# Recurse into iterable values (or dict keys).
var_datas.extend(_extract_var_data(sub))
# Style objects should already have _var_data.
if isinstance(value, Style):
var_datas.append(value._var_data)
else:
# Recurse when value is a dict itself.
values = getattr(value, "values", None)
if callable(values):
var_datas.extend(_extract_var_data(values()))
return var_datas
class Var:
"""An abstract var."""
# The name of the var.
_var_name: str
# The type of the var.
_var_type: Type
# Whether this is a local javascript variable.
_var_is_local: bool
# Whether the var is a string literal.
_var_is_string: bool
# _var_full_name should be prefixed with _var_state
_var_full_name_needs_state_prefix: bool
# Extra metadata associated with the Var
_var_data: Optional[VarData]
@classmethod
def create(
cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
) -> Var | None:
"""Create a var from a value.
Args:
value: The value to create the var from.
_var_is_local: Whether the var is local.
_var_is_string: Whether the var is a string literal.
Returns:
The var.
Raises:
TypeError: If the value is JSON-unserializable.
"""
# Check for none values.
if value is None:
return None
# If the value is already a var, do nothing.
if isinstance(value, Var):
return value
# Try to pull the imports and hooks from contained values.
_var_data = None
if not isinstance(value, str):
_var_data = VarData.merge(*_extract_var_data(value))
# Try to serialize the value.
type_ = type(value)
name = value if type_ in types.JSONType else serializers.serialize(value)
if name is None:
raise TypeError(
f"No JSON serializer found for var {value} of type {type_}."
)
name = name if isinstance(name, str) else format.json_dumps(name)
return BaseVar(
_var_name=name,
_var_type=type_,
_var_is_local=_var_is_local,
_var_is_string=_var_is_string,
_var_data=_var_data,
)
@classmethod
def create_safe(
cls, value: Any, _var_is_local: bool = True, _var_is_string: bool = False
) -> Var:
"""Create a var from a value, asserting that it is not None.
Args:
value: The value to create the var from.
_var_is_local: Whether the var is local.
_var_is_string: Whether the var is a string literal.
Returns:
The var.
"""
var = cls.create(
value,
_var_is_local=_var_is_local,
_var_is_string=_var_is_string,
)
assert var is not None
return var
@classmethod
def __class_getitem__(cls, type_: str) -> _GenericAlias:
"""Get a typed var.
Args:
type_: The type of the var.
Returns:
The var class item.
"""
return _GenericAlias(cls, type_)
def __post_init__(self) -> None:
"""Post-initialize the var."""
# Decode any inline Var markup and apply it to the instance
_var_data, _var_name = _decode_var(self._var_name)
if _var_data:
self._var_name = _var_name
self._var_data = VarData.merge(self._var_data, _var_data)
def _replace(self, merge_var_data=None, **kwargs: Any) -> Var:
"""Make a copy of this Var with updated fields.
Args:
merge_var_data: VarData to merge into the existing VarData.
**kwargs: Var fields to update.
Returns:
A new BaseVar with the updated fields overwriting the corresponding fields in this Var.
"""
field_values = dict(
_var_name=kwargs.pop("_var_name", self._var_name),
_var_type=kwargs.pop("_var_type", self._var_type),
_var_is_local=kwargs.pop("_var_is_local", self._var_is_local),
_var_is_string=kwargs.pop("_var_is_string", self._var_is_string),
_var_full_name_needs_state_prefix=kwargs.pop(
"_var_full_name_needs_state_prefix",
self._var_full_name_needs_state_prefix,
),
_var_data=VarData.merge(
kwargs.get("_var_data", self._var_data), merge_var_data
),
)
return BaseVar(**field_values)
def _decode(self) -> Any:
"""Decode Var as a python value.
Note that Var with state set cannot be decoded python-side and will be
returned as full_name.
Returns:
The decoded value or the Var name.
"""
if self._var_is_string:
return self._var_name
try:
return json.loads(self._var_name)
except ValueError:
return self._var_name
def equals(self, other: Var) -> bool:
"""Check if two vars are equal.
Args:
other: The other var to compare.
Returns:
Whether the vars are equal.
"""
return (
self._var_name == other._var_name
and self._var_type == other._var_type
and self._var_is_local == other._var_is_local
and self._var_full_name_needs_state_prefix
== other._var_full_name_needs_state_prefix
and self._var_data == other._var_data
)
def _merge(self, other) -> Var:
"""Merge two or more dicts.
Args:
other: The other var to merge.
Returns:
The merged var.
"""
if other is None:
return self._replace()
if not isinstance(other, Var):
other = Var.create(other)
return self._replace(
_var_name=f"{{...{self._var_name}, ...{other._var_name}}}" # type: ignore
)
def to_string(self, json: bool = True) -> Var:
"""Convert a var to a string.
Args:
json: Whether to convert to a JSON string.
Returns:
The stringified var.
"""
fn = "JSON.stringify" if json else "String"
return self.operation(fn=fn, type_=str)
def __hash__(self) -> int:
"""Define a hash function for a var.
Returns:
The hash of the var.
"""
return hash((self._var_name, str(self._var_type)))
def __str__(self) -> str:
"""Wrap the var so it can be used in templates.
Returns:
The wrapped var, i.e. {state.var}.
"""
out = (
self._var_full_name
if self._var_is_local
else format.wrap(self._var_full_name, "{")
)
if self._var_is_string:
out = format.format_string(out)
return out
def __bool__(self) -> bool:
"""Raise exception if using Var in a boolean context.
Raises:
TypeError: when attempting to bool-ify the Var.
"""
raise TypeError(
f"Cannot convert Var {self._var_full_name!r} to bool for use with `if`, `and`, `or`, and `not`. "
"Instead use `rx.cond` and bitwise operators `&` (and), `|` (or), `~` (invert)."
)
def __iter__(self) -> Any:
"""Raise exception if using Var in an iterable context.
Raises:
TypeError: when attempting to iterate over the Var.
"""
raise TypeError(
f"Cannot iterate over Var {self._var_full_name!r}. Instead use `rx.foreach`."
)
def __format__(self, format_spec: str) -> str:
"""Format the var into a Javascript equivalent to an f-string.
Args:
format_spec: The format specifier (Ignored for now).
Returns:
The formatted var.
"""
# Encode the _var_data into the formatted output for tracking purposes.
str_self = _encode_var(self)
if self._var_is_local:
return str_self
return f"${str_self}"
def __getitem__(self, i: Any) -> Var:
"""Index into a var.
Args:
i: The index to index into.
Returns:
The indexed var.
Raises:
TypeError: If the var is not indexable.
"""
# Indexing is only supported for strings, lists, tuples, dicts, and dataframes.
if not (
types._issubclass(self._var_type, Union[List, Dict, Tuple, str])
or types.is_dataframe(self._var_type)
):
if self._var_type == Any:
raise TypeError(
"Could not index into var of type Any. (If you are trying to index into a state var, "
"add the correct type annotation to the var.)"
)
raise TypeError(
f"Var {self._var_name} of type {self._var_type} does not support indexing."
)
# The type of the indexed var.
type_ = Any
# Convert any vars to local vars.
if isinstance(i, Var):
i = i._replace(_var_is_local=True)
# Handle list/tuple/str indexing.
if types._issubclass(self._var_type, Union[List, Tuple, str]):
# List/Tuple/String indices must be ints, slices, or vars.
if (
not isinstance(i, types.get_args(Union[int, slice, Var]))
or isinstance(i, Var)
and not i._var_type == int
):
raise TypeError("Index must be an integer or an integer var.")
# Handle slices first.
if isinstance(i, slice):
# Get the start and stop indices.
start = i.start or 0
stop = i.stop or "undefined"
# Use the slice function.
return self._replace(
_var_name=f"{self._var_name}.slice({start}, {stop})",
_var_is_string=False,
)
# Get the type of the indexed var.
if types.is_generic_alias(self._var_type):
index = i if not isinstance(i, Var) else 0
type_ = types.get_args(self._var_type)
type_ = type_[index%len(type_)]
elif types._issubclass(self._var_type, str):
type_ = str
# Use `at` to support negative indices.
return self._replace(
_var_name=f"{self._var_name}.at({i})",
_var_type=type_,
_var_is_string=False,
)
# Dictionary / dataframe indexing.
# Tuples are currently not supported as indexes.
if (
(
types._issubclass(self._var_type, Dict)
or types.is_dataframe(self._var_type)
)
and not isinstance(i, types.get_args(Union[int, str, float, Var]))
) or (
isinstance(i, Var)
and not types._issubclass(
i._var_type, types.get_args(Union[int, str, float])
)
):
raise TypeError(
"Index must be one of the following types: int, str, int or str Var"
)
# Get the type of the indexed var.
if isinstance(i, str):
i = format.wrap(i, '"')
type_ = (
types.get_args(self._var_type)[1]
if types.is_generic_alias(self._var_type)
else Any
)
# Use normal indexing here.
return self._replace(
_var_name=f"{self._var_name}[{i}]",
_var_type=type_,
_var_is_string=False,
)
def __getattr__(self, name: str) -> Var:
"""Get a var attribute.
Args:
name: The name of the attribute.
Returns:
The var attribute.
Raises:
AttributeError: If the var is wrongly annotated or can't find attribute.
TypeError: If an annotation to the var isn't provided.
"""
# Check if the attribute is one of the class fields.
if not name.startswith("_"):
if self._var_type == Any:
raise TypeError(
f"You must provide an annotation for the state var `{self._var_full_name}`. Annotation cannot be `{self._var_type}`"
) from None
is_optional = types.is_optional(self._var_type)
type_ = types.get_attribute_access_type(self._var_type, name)
if type_ is not None:
return self._replace(
_var_name=f"{self._var_name}{'?' if is_optional else ''}.{name}",
_var_type=type_,
_var_is_string=False,
)
if name in REPLACED_NAMES:
raise AttributeError(
f"Field {name!r} was renamed to {REPLACED_NAMES[name]!r}"
)
raise AttributeError(
f"The State var `{self._var_full_name}` has no attribute '{name}' or may have been annotated "
f"wrongly."
)
raise AttributeError(
f"The State var has no attribute '{name}' or may have been annotated wrongly.",
)
def operation(
self,
op: str = "",
other: Var | None = None,
type_: Type | None = None,
flip: bool = False,
fn: str | None = None,
invoke_fn: bool = False,
) -> Var:
"""Perform an operation on a var.
Args:
op: The operation to perform.
other: The other var to perform the operation on.
type_: The type of the operation result.
flip: Whether to flip the order of the operation.
fn: A function to apply to the operation.
invoke_fn: Whether to invoke the function.
Returns:
The operation result.
Raises:
TypeError: If the operation between two operands is invalid.
ValueError: If flip is set to true and value of operand is not provided
"""
if isinstance(other, str):
other = Var.create(json.dumps(other))
else:
other = Var.create(other)
type_ = type_ or self._var_type
if other is None and flip:
raise ValueError(
"flip_operands cannot be set to True if the value of 'other' operand is not provided"
)
left_operand, right_operand = (other, self) if flip else (self, other)
def get_operand_full_name(operand):
# operand vars that are string literals need to be wrapped in back ticks.
return (
operand._var_name_unwrapped
if operand._var_is_string
and not operand._var_state
and operand._var_is_local
else operand._var_full_name
)
if other is not None:
# check if the operation between operands is valid.
if op and not self.is_valid_operation(
types.get_base_class(left_operand._var_type), # type: ignore
types.get_base_class(right_operand._var_type), # type: ignore
op,
):
raise TypeError(
f"Unsupported Operand type(s) for {op}: `{left_operand._var_full_name}` of type {left_operand._var_type.__name__} and `{right_operand._var_full_name}` of type {right_operand._var_type.__name__}" # type: ignore
)
left_operand_full_name = get_operand_full_name(left_operand)
right_operand_full_name = get_operand_full_name(right_operand)
# apply function to operands
if fn is not None:
if invoke_fn:
# invoke the function on left operand.
operation_name = f"{left_operand_full_name}.{fn}({right_operand_full_name})" # type: ignore
else:
# pass the operands as arguments to the function.
operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
operation_name = f"{fn}({operation_name})"
else:
# apply operator to operands (left operand <operator> right_operand)
operation_name = f"{left_operand_full_name} {op} {right_operand_full_name}" # type: ignore
operation_name = format.wrap(operation_name, "(")
else:
# apply operator to left operand (<operator> left_operand)
operation_name = f"{op}{get_operand_full_name(self)}"
# apply function to operands
if fn is not None:
operation_name = (
f"{fn}({operation_name})"
if not invoke_fn
else f"{get_operand_full_name(self)}.{fn}()"
)
return self._replace(
_var_name=operation_name,
_var_type=type_,
_var_is_string=False,
_var_full_name_needs_state_prefix=False,
merge_var_data=other._var_data if other is not None else None,
)
@staticmethod
def is_valid_operation(
operand1_type: Type, operand2_type: Type, operator: str
) -> bool:
"""Check if an operation between two operands is valid.
Args:
operand1_type: Type of the operand
operand2_type: Type of the second operand
operator: The operator.
Returns:
Whether operation is valid or not
"""
if operator in ALL_OPS or operator in DELIMITERS:
return True
# bools are subclasses of ints
pair = tuple(
sorted(
[
int if operand1_type == bool else operand1_type,
int if operand2_type == bool else operand2_type,
],
key=lambda x: x.__name__,
)
)
return pair in OPERATION_MAPPING and operator in OPERATION_MAPPING[pair]
def compare(self, op: str, other: Var) -> Var:
"""Compare two vars with inequalities.
Args:
op: The comparison operator.
other: The other var to compare with.
Returns:
The comparison result.
"""
return self.operation(op, other, bool)
def __invert__(self) -> Var:
"""Invert a var.
Returns:
The inverted var.
"""
return self.operation("!", type_=bool)
def __neg__(self) -> Var:
"""Negate a var.
Returns:
The negated var.
"""
return self.operation(fn="-")
def __abs__(self) -> Var:
"""Get the absolute value of a var.
Returns:
A var with the absolute value.
"""
return self.operation(fn="Math.abs")
def length(self) -> Var:
"""Get the length of a list var.
Returns:
A var with the absolute value.
Raises:
TypeError: If the var is not a list.
"""
if not types._issubclass(self._var_type, List):
raise TypeError(f"Cannot get length of non-list var {self}.")
return self._replace(
_var_name=f"{self._var_name}.length",
_var_type=int,
_var_is_string=False,
)
def _type(self) -> Var:
"""Get the type of the Var in Javascript.
Returns:
A var representing the type check.
"""
return self._replace(
_var_name=f"typeof {self._var_full_name}",
_var_type=str,
_var_is_string=False,
_var_full_name_needs_state_prefix=False,
)
def __eq__(self, other: Union[Var, Type]) -> Var:
"""Perform an equality comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the equality comparison.
"""
for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
if not isinstance(other, Var) and other in python_types:
return self.compare("===", Var.create(js_type, _var_is_string=True)) # type: ignore
return self.compare("===", other)
def __ne__(self, other: Union[Var, Type]) -> Var:
"""Perform an inequality comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the inequality comparison.
"""
for python_types, js_type in PYTHON_JS_TYPE_MAP.items():
if not isinstance(other, Var) and other in python_types:
return self.compare("!==", Var.create(js_type, _var_is_string=True)) # type: ignore
return self.compare("!==", other)
def __gt__(self, other: Var) -> Var:
"""Perform a greater than comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the greater than comparison.
"""
return self.compare(">", other)
def __ge__(self, other: Var) -> Var:
"""Perform a greater than or equal to comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the greater than or equal to comparison.
"""
return self.compare(">=", other)
def __lt__(self, other: Var) -> Var:
"""Perform a less than comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the less than comparison.
"""
return self.compare("<", other)
def __le__(self, other: Var) -> Var:
"""Perform a less than or equal to comparison.
Args:
other: The other var to compare with.
Returns:
A var representing the less than or equal to comparison.
"""
return self.compare("<=", other)
def __add__(self, other: Var, flip=False) -> Var:
"""Add two vars.
Args:
other: The other var to add.
flip: Whether to flip operands.
Returns:
A var representing the sum.
"""
other_type = other._var_type if isinstance(other, Var) else type(other)
# For list-list addition, javascript concatenates the content of the lists instead of
# merging the list, and for that reason we use the spread operator available through spreadArraysOrObjects
# utility function
if (
types.get_base_class(self._var_type) == list
and types.get_base_class(other_type) == list
):
return self.operation(
",", other, fn="spreadArraysOrObjects", flip=flip
)._replace(
merge_var_data=VarData(
imports={
f"/{constants.Dirs.STATE_PATH}": [
ImportVar(tag="spreadArraysOrObjects")
]
},
),
)
return self.operation("+", other, flip=flip)
def __radd__(self, other: Var) -> Var:
"""Add two vars.
Args:
other: The other var to add.
Returns:
A var representing the sum.
"""
return self.__add__(other=other, flip=True)
def __sub__(self, other: Var) -> Var:
"""Subtract two vars.
Args:
other: The other var to subtract.
Returns:
A var representing the difference.
"""
return self.operation("-", other)
def __rsub__(self, other: Var) -> Var:
"""Subtract two vars.
Args:
other: The other var to subtract.
Returns: