-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathbase.py
More file actions
3725 lines (2960 loc) ยท 111 KB
/
Copy pathbase.py
File metadata and controls
3725 lines (2960 loc) ยท 111 KB
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
"""Collection of base classes."""
from __future__ import annotations
import contextlib
import copy
import dataclasses
import datetime
import functools
import inspect
import json
import re
import string
import uuid
import warnings
from abc import ABCMeta
from collections.abc import Callable, Coroutine, Iterable, Mapping, Sequence
from dataclasses import _MISSING_TYPE, MISSING
from decimal import Decimal
from types import CodeType, FunctionType
from typing import (
TYPE_CHECKING,
Annotated,
Any,
ClassVar,
Generic,
Literal,
NoReturn,
ParamSpec,
Protocol,
TypeGuard,
TypeVar,
cast,
get_args,
get_type_hints,
overload,
)
from rich.markup import escape
from typing_extensions import LiteralString, dataclass_transform, override
from reflex_base import constants
from reflex_base.constants.compiler import Hooks
from reflex_base.constants.state import FIELD_MARKER
from reflex_base.utils import console, exceptions, imports, serializers, types
from reflex_base.utils.compat import annotations_from_namespace
from reflex_base.utils.decorator import once
from reflex_base.utils.exceptions import (
ComputedVarSignatureError,
UntypedComputedVarError,
VarAttributeError,
VarDependencyError,
VarTypeError,
)
from reflex_base.utils.format import format_state_name
from reflex_base.utils.imports import (
ImmutableImportDict,
ImmutableParsedImportDict,
ImportDict,
ImportVar,
ParsedImportTuple,
parse_imports,
)
from reflex_base.utils.types import (
GenericType,
Self,
_isinstance,
get_origin,
has_args,
safe_issubclass,
unionize,
)
if TYPE_CHECKING:
from reflex.state import BaseState
from reflex_base.components.component import BaseComponent
from reflex_base.constants.colors import Color
from .color import LiteralColorVar
from .number import BooleanVar, LiteralBooleanVar, LiteralNumberVar, NumberVar
from .object import LiteralObjectVar, ObjectVar
from .sequence import ArrayVar, LiteralArrayVar, LiteralStringVar, StringVar
VAR_TYPE = TypeVar("VAR_TYPE", covariant=True)
OTHER_VAR_TYPE = TypeVar("OTHER_VAR_TYPE")
STRING_T = TypeVar("STRING_T", bound=str)
LITERAL_STRING_T = TypeVar("LITERAL_STRING_T", bound=LiteralString)
SEQUENCE_TYPE = TypeVar("SEQUENCE_TYPE", bound=Sequence)
warnings.filterwarnings("ignore", message="fields may not start with an underscore")
_PYDANTIC_VALIDATE_VALUES = "__pydantic_validate_values__"
def _pydantic_validator(*args, **kwargs):
return None
@dataclasses.dataclass(
eq=False,
frozen=True,
)
class VarSubclassEntry:
"""Entry for a Var subclass."""
var_subclass: type[Var]
to_var_subclass: type[ToOperation]
python_types: tuple[GenericType, ...]
_var_subclasses: list[VarSubclassEntry] = []
_var_literal_subclasses: list[tuple[type[LiteralVar], VarSubclassEntry]] = []
@dataclasses.dataclass(
eq=True,
frozen=True,
)
class VarData:
"""Metadata associated with a x."""
# The name of the enclosing state.
state: str = dataclasses.field(default="")
# The name of the field in the state.
field_name: str = dataclasses.field(default="")
# Imports needed to render this var
imports: ParsedImportTuple = dataclasses.field(default_factory=tuple)
# Hooks that need to be present in the component to render this var
hooks: tuple[str, ...] = dataclasses.field(default_factory=tuple)
# Dependencies of the var
deps: tuple[Var, ...] = dataclasses.field(default_factory=tuple)
# Position of the hook in the component
position: Hooks.HookPosition | None = None
# Components that are part of this var
components: tuple[BaseComponent, ...] = dataclasses.field(default_factory=tuple)
# Module-level JS snippets this var contributes to the page (top-of-file helpers/constants)
module_code: tuple[str, ...] = dataclasses.field(default_factory=tuple)
def __init__(
self,
state: str = "",
field_name: str = "",
imports: ImmutableImportDict | ImmutableParsedImportDict | None = None,
hooks: Mapping[str, VarData | None] | Sequence[str] | str | None = None,
deps: list[Var] | None = None,
position: Hooks.HookPosition | None = None,
components: Iterable[BaseComponent] | None = None,
module_code: Iterable[str] | None = None,
):
"""Initialize the var data.
Args:
state: The name of the enclosing state.
field_name: The name of the field in the state.
imports: Imports needed to render this var.
hooks: Hooks that need to be present in the component to render this var.
deps: Dependencies of the var for useCallback.
position: Position of the hook in the component.
components: Components that are part of this var.
module_code: Module-level JS snippets this var contributes to the page.
"""
if isinstance(hooks, str):
hooks = [hooks]
if not isinstance(hooks, dict):
hooks = dict.fromkeys(hooks or [])
immutable_imports: ParsedImportTuple = tuple(
(k, tuple(v)) for k, v in parse_imports(imports or {}).items()
)
object.__setattr__(self, "state", state)
object.__setattr__(self, "field_name", field_name)
object.__setattr__(self, "imports", immutable_imports)
object.__setattr__(self, "hooks", tuple(hooks or {}))
object.__setattr__(self, "deps", tuple(deps or []))
object.__setattr__(self, "position", position or None)
object.__setattr__(self, "components", tuple(components or []))
object.__setattr__(self, "module_code", tuple(module_code or []))
if hooks and any(hooks.values()):
# Merge our dependencies first, so they can be referenced.
merged_var_data = VarData.merge(*hooks.values(), self)
if merged_var_data is not None:
object.__setattr__(self, "state", merged_var_data.state)
object.__setattr__(self, "field_name", merged_var_data.field_name)
object.__setattr__(self, "imports", merged_var_data.imports)
object.__setattr__(self, "hooks", merged_var_data.hooks)
object.__setattr__(self, "deps", merged_var_data.deps)
object.__setattr__(self, "position", merged_var_data.position)
object.__setattr__(self, "components", merged_var_data.components)
object.__setattr__(self, "module_code", merged_var_data.module_code)
def old_school_imports(self) -> ImportDict:
"""Return the imports as a mutable dict.
Returns:
The imports as a mutable dict.
"""
return {k: list(v) for k, v in self.imports}
def merge(*all: VarData | None) -> VarData | None:
"""Merge multiple var data objects.
Args:
*all: The var data objects to merge.
Returns:
The merged var data object.
Raises:
ReflexError: If trying to merge VarData with different positions.
# noqa: DAR102 *all
"""
all_var_datas = list(filter(None, all))
if not all_var_datas:
return None
if len(all_var_datas) == 1:
return all_var_datas[0]
# Get the first non-empty field name or default to empty string.
field_name = next(
(var_data.field_name for var_data in all_var_datas if var_data.field_name),
"",
)
# Get the first non-empty state or default to empty string.
state = next(
(var_data.state for var_data in all_var_datas if var_data.state), ""
)
hooks: dict[str, VarData | None] = {
hook: None for var_data in all_var_datas for hook in var_data.hooks
}
imports_ = imports.merge_imports(
*(var_data.imports for var_data in all_var_datas)
)
deps = [dep for var_data in all_var_datas for dep in var_data.deps]
positions = list(
dict.fromkeys(
var_data.position
for var_data in all_var_datas
if var_data.position is not None
)
)
if positions:
if len(positions) > 1:
msg = f"Cannot merge var data with different positions: {positions}"
raise exceptions.ReflexError(msg)
position = positions[0]
else:
position = None
components = tuple(
component for var_data in all_var_datas for component in var_data.components
)
module_code = tuple(
dict.fromkeys(
snippet
for var_data in all_var_datas
for snippet in var_data.module_code
)
)
return VarData(
state=state,
field_name=field_name,
imports=imports_,
hooks=hooks,
deps=deps,
position=position,
components=components,
module_code=module_code,
)
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
or self.field_name
or self.deps
or self.position
or self.components
or self.module_code
)
@classmethod
def from_state(cls, state: type[BaseState] | str, field_name: str = "") -> VarData:
"""Set the state of the var.
Args:
state: The state to set or the full name of the state.
field_name: The name of the field in the state. Optional.
Returns:
The var with the set state.
"""
from reflex_base.utils import format
state_name = state if isinstance(state, str) else state.get_full_name()
return VarData(
state=state_name,
field_name=field_name,
hooks={
"const {0} = useContext(StateContexts.{0})".format(
format.format_state_name(state_name)
): None
},
imports={
f"$/{constants.Dirs.CONTEXTS_PATH}": [ImportVar(tag="StateContexts")],
"react": [ImportVar(tag="useContext")],
},
)
def _decode_var_immutable(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):
# fast path if there is no encoded VarData
if constants.REFLEX_VAR_OPENING_TAG not in value:
return None, value
offset = 0
# Find all tags.
while m := _decode_var_pattern.search(value):
start, end = m.span()
value = value[:start] + value[end:]
serialized_data = m.group(1)
if serialized_data.isnumeric() or (
serialized_data[0] == "-" and serialized_data[1:].isnumeric()
):
# This is a global immutable var.
var = _global_vars[int(serialized_data)]
var_data = var._get_all_var_data()
if var_data is not None:
var_datas.append(var_data)
offset += end - start
return VarData.merge(*var_datas) if var_datas else None, value
def can_use_in_object_var(cls: GenericType) -> bool:
"""Check if the class can be used in an ObjectVar.
Args:
cls: The class to check.
Returns:
Whether the class can be used in an ObjectVar.
"""
if types.is_union(cls):
return all(can_use_in_object_var(t) for t in get_args(cls))
return (
isinstance(cls, type)
and not safe_issubclass(cls, Var)
and serializers.can_serialize(cls, dict)
)
class MetaclassVar(type):
"""Metaclass for the Var class."""
def __setattr__(cls, name: str, value: Any):
"""Set an attribute on the class.
Args:
name: The name of the attribute.
value: The value of the attribute.
"""
super().__setattr__(
name, value if name != _PYDANTIC_VALIDATE_VALUES else _pydantic_validator
)
@dataclasses.dataclass(
eq=False,
frozen=True,
)
class Var(Generic[VAR_TYPE], metaclass=MetaclassVar):
"""Base class for immutable vars."""
# The name of the var.
_js_expr: str = dataclasses.field()
# The type of the var.
_var_type: types.GenericType = dataclasses.field(default=Any)
# Extra metadata associated with the Var
_var_data: VarData | None = dataclasses.field(default=None)
def __str__(self) -> str:
"""String representation of the var. Guaranteed to be a valid Javascript expression.
Returns:
The name of the var.
"""
return self._js_expr
@property
def _var_is_local(self) -> bool:
"""Whether this is a local javascript variable.
Returns:
False
"""
return False
@property
def _var_is_string(self) -> bool:
"""Whether the var is a string literal.
Returns:
False
"""
return False
def __init_subclass__(
cls,
python_types: tuple[GenericType, ...] | GenericType = types.Unset(),
default_type: GenericType = types.Unset(),
**kwargs,
):
"""Initialize the subclass.
Args:
python_types: The python types that the var represents.
default_type: The default type of the var. Defaults to the first python type.
**kwargs: Additional keyword arguments.
"""
super().__init_subclass__(**kwargs)
if python_types or default_type:
python_types = (
(python_types if isinstance(python_types, tuple) else (python_types,))
if python_types
else ()
)
default_type = default_type or (python_types[0] if python_types else Any)
@dataclasses.dataclass(
eq=False,
frozen=True,
slots=True,
)
class ToVarOperation(ToOperation, cls):
"""Base class of converting a var to another var type."""
_original: Var = dataclasses.field(
default=Var(_js_expr="null", _var_type=None),
)
_default_var_type: ClassVar[GenericType] = default_type
new_to_var_operation_name = f"{cls.__name__.removesuffix('Var')}CastedVar"
ToVarOperation.__qualname__ = (
ToVarOperation.__qualname__.removesuffix(ToVarOperation.__name__)
+ new_to_var_operation_name
)
ToVarOperation.__name__ = new_to_var_operation_name
_var_subclasses.append(VarSubclassEntry(cls, ToVarOperation, python_types))
def __post_init__(self):
"""Post-initialize the var.
Raises:
TypeError: If _js_expr is not a string.
"""
if not isinstance(self._js_expr, str):
msg = f"Expected _js_expr to be a string, got value {self._js_expr!r} of type {type(self._js_expr).__name__}"
raise TypeError(msg)
if self._var_data is not None and not isinstance(self._var_data, VarData):
msg = f"Expected _var_data to be a VarData, got value {self._var_data!r} of type {type(self._var_data).__name__}"
raise TypeError(msg)
# Decode any inline Var markup and apply it to the instance
var_data_, js_expr_ = _decode_var_immutable(self._js_expr)
if var_data_ or js_expr_ != self._js_expr:
self.__init__(
_js_expr=js_expr_,
_var_type=self._var_type,
_var_data=VarData.merge(self._var_data, var_data_),
)
def __hash__(self) -> int:
"""Define a hash function for the var.
Returns:
The hash of the var.
"""
return hash((self._js_expr, self._var_type, self._var_data))
def _get_all_var_data(self) -> VarData | None:
"""Get all VarData associated with the Var.
Returns:
The VarData of the components and all of its children.
"""
return self._var_data
def __deepcopy__(self, memo: dict[int, Any]) -> Self:
"""Deepcopy the var.
Args:
memo: The memo dictionary to use for the deepcopy.
Returns:
A deepcopy of the var.
"""
return self
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._js_expr == other._js_expr
and self._var_type == other._var_type
and self._get_all_var_data() == other._get_all_var_data()
)
@overload
def _replace(
self,
_var_type: type[OTHER_VAR_TYPE],
merge_var_data: VarData | None = None,
**kwargs: Any,
) -> Var[OTHER_VAR_TYPE]: ...
@overload
def _replace(
self,
_var_type: GenericType | None = None,
merge_var_data: VarData | None = None,
**kwargs: Any,
) -> Self: ...
def _replace(
self,
_var_type: GenericType | None = None,
merge_var_data: VarData | None = None,
**kwargs: Any,
) -> Self | Var:
"""Make a copy of this Var with updated fields.
Args:
_var_type: The new type of the Var.
merge_var_data: VarData to merge into the existing VarData.
**kwargs: Var fields to update.
Returns:
A new Var with the updated fields overwriting the corresponding fields in this Var.
Raises:
TypeError: If _var_is_local, _var_is_string, or _var_full_name_needs_state_prefix is not None.
"""
if kwargs.get("_var_is_local", False) is not False:
msg = "The _var_is_local argument is not supported for Var."
raise TypeError(msg)
if kwargs.get("_var_is_string", False) is not False:
msg = "The _var_is_string argument is not supported for Var."
raise TypeError(msg)
if kwargs.get("_var_full_name_needs_state_prefix", False) is not False:
msg = "The _var_full_name_needs_state_prefix argument is not supported for Var."
raise TypeError(msg)
value_with_replaced = dataclasses.replace(
self,
_var_type=_var_type or self._var_type,
_var_data=VarData.merge(
kwargs.get("_var_data", self._var_data), merge_var_data
),
**kwargs,
)
if (js_expr := kwargs.get("_js_expr")) is not None:
object.__setattr__(value_with_replaced, "_js_expr", js_expr)
return value_with_replaced
@overload
@classmethod
def create( # pyright: ignore[reportOverlappingOverload]
cls,
value: NoReturn,
_var_data: VarData | None = None,
) -> Var[Any]: ...
@overload
@classmethod
def create( # pyright: ignore[reportOverlappingOverload]
cls,
value: bool,
_var_data: VarData | None = None,
) -> LiteralBooleanVar: ...
@overload
@classmethod
def create(
cls,
value: int,
_var_data: VarData | None = None,
) -> LiteralNumberVar[int]: ...
@overload
@classmethod
def create(
cls,
value: float,
_var_data: VarData | None = None,
) -> LiteralNumberVar[float]: ...
@overload
@classmethod
def create(
cls,
value: Decimal,
_var_data: VarData | None = None,
) -> LiteralNumberVar[Decimal]: ...
@overload
@classmethod
def create( # pyright: ignore [reportOverlappingOverload]
cls,
value: Color,
_var_data: VarData | None = None,
) -> LiteralColorVar: ...
@overload
@classmethod
def create( # pyright: ignore [reportOverlappingOverload]
cls,
value: LITERAL_STRING_T,
_var_data: VarData | None = None,
) -> LiteralStringVar[LITERAL_STRING_T]: ...
@overload
@classmethod
def create( # pyright: ignore [reportOverlappingOverload]
cls,
value: STRING_T,
_var_data: VarData | None = None,
) -> StringVar[STRING_T]: ...
@overload
@classmethod
def create( # pyright: ignore[reportOverlappingOverload]
cls,
value: None,
_var_data: VarData | None = None,
) -> LiteralNoneVar: ...
@overload
@classmethod
def create(
cls,
value: MAPPING_TYPE,
_var_data: VarData | None = None,
) -> LiteralObjectVar[MAPPING_TYPE]: ...
@overload
@classmethod
def create(
cls,
value: SEQUENCE_TYPE,
_var_data: VarData | None = None,
) -> LiteralArrayVar[SEQUENCE_TYPE]: ...
@overload
@classmethod
def create(
cls,
value: OTHER_VAR_TYPE,
_var_data: VarData | None = None,
) -> Var[OTHER_VAR_TYPE]: ...
@classmethod
def create(
cls,
value: OTHER_VAR_TYPE,
_var_data: VarData | None = None,
) -> Var[OTHER_VAR_TYPE]:
"""Create a var from a value.
Args:
value: The value to create the var from.
_var_data: Additional hooks and imports associated with the Var.
Returns:
The var.
"""
# If the value is already a var, do nothing.
if isinstance(value, Var):
return value
return LiteralVar.create(value, _var_data=_var_data)
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.
"""
hashed_var = hash(self)
_global_vars[hashed_var] = self
# Encode the _var_data into the formatted output for tracking purposes.
return f"{constants.REFLEX_VAR_OPENING_TAG}{hashed_var}{constants.REFLEX_VAR_CLOSING_TAG}{self._js_expr}"
@overload
def to(self, output: type[str]) -> StringVar: ... # pyright: ignore[reportOverlappingOverload]
@overload
def to(self, output: type[bool]) -> BooleanVar: ...
@overload
def to(self, output: type[int]) -> NumberVar[int]: ...
@overload
def to(self, output: type[float]) -> NumberVar[float]: ...
@overload
def to(self, output: type[Decimal]) -> NumberVar[Decimal]: ...
@overload
def to(
self,
output: type[SEQUENCE_TYPE],
) -> ArrayVar[SEQUENCE_TYPE]: ...
@overload
def to(
self,
output: type[MAPPING_TYPE],
) -> ObjectVar[MAPPING_TYPE]: ...
@overload
def to(
self, output: type[ObjectVar], var_type: type[VAR_INSIDE]
) -> ObjectVar[VAR_INSIDE]: ...
@overload
def to(
self, output: type[ObjectVar], var_type: None = None
) -> ObjectVar[VAR_TYPE]: ...
@overload
def to(self, output: VAR_SUBCLASS, var_type: None = None) -> VAR_SUBCLASS: ...
@overload
def to(
self,
output: type[OUTPUT] | types.GenericType,
var_type: types.GenericType | None = None,
) -> OUTPUT: ...
def to(
self,
output: type[OUTPUT] | types.GenericType,
var_type: types.GenericType | None = None,
) -> Var:
"""Convert the var to a different type.
Args:
output: The output type.
var_type: The type of the var.
Returns:
The converted var.
"""
from .object import ObjectVar
fixed_output_type = get_origin(output) or output
# If the first argument is a python type, we map it to the corresponding Var type.
for var_subclass in _var_subclasses[::-1]:
if fixed_output_type in var_subclass.python_types or safe_issubclass(
fixed_output_type, var_subclass.python_types
):
return self.to(var_subclass.var_subclass, output)
if fixed_output_type is None:
return get_to_operation(NoneVar).create(self) # pyright: ignore [reportReturnType]
# Handle fixed_output_type being Base or a dataclass.
if can_use_in_object_var(output):
return self.to(ObjectVar, output)
if isinstance(output, type):
for var_subclass in _var_subclasses[::-1]:
if safe_issubclass(output, var_subclass.var_subclass):
current_var_type = self._var_type
if current_var_type is Any:
new_var_type = var_type
else:
new_var_type = var_type or current_var_type
return var_subclass.to_var_subclass.create( # pyright: ignore [reportReturnType]
value=self, _var_type=new_var_type
)
# If we can't determine the first argument, we just replace the _var_type.
if not safe_issubclass(output, Var) or var_type is None:
return dataclasses.replace(
self,
_var_type=output,
)
# We couldn't determine the output type to be any other Var type, so we replace the _var_type.
if var_type is not None:
return dataclasses.replace(
self,
_var_type=var_type,
)
return self
@overload
def guess_type(self: Var[NoReturn]) -> Var[Any]: ... # pyright: ignore [reportOverlappingOverload]
@overload
def guess_type(self: Var[str]) -> StringVar: ...
@overload
def guess_type(self: Var[bool]) -> BooleanVar: ...
@overload
def guess_type(self: Var[int] | Var[float] | Var[int | float]) -> NumberVar: ...
@overload
def guess_type(self) -> Self: ...
def guess_type(self) -> Var:
"""Guesses the type of the variable based on its `_var_type` attribute.
Returns:
Var: The guessed type of the variable.
Raises:
TypeError: If the type is not supported for guessing.
"""
from .object import ObjectVar
var_type = self._var_type
if var_type is None:
return self.to(None)
if var_type is NoReturn:
return self.to(Any)
var_type = types.value_inside_optional(var_type)
if var_type is Any:
return self
fixed_type = get_origin(var_type) or var_type
if fixed_type in types.UnionTypes:
inner_types = get_args(var_type)
non_optional_inner_types = [
types.value_inside_optional(inner_type) for inner_type in inner_types
]
fixed_inner_types = [
get_origin(inner_type) or inner_type
for inner_type in non_optional_inner_types
]
for var_subclass in _var_subclasses[::-1]:
if all(
safe_issubclass(t, var_subclass.python_types)
for t in fixed_inner_types
):
return self.to(var_subclass.var_subclass, self._var_type)
if can_use_in_object_var(var_type):
return self.to(ObjectVar, self._var_type)
return self
if fixed_type is Literal:
args = get_args(var_type)
fixed_type = unionize(*(type(arg) for arg in args))
if not isinstance(fixed_type, type):
msg = f"Unsupported type {var_type} for guess_type."
raise TypeError(msg)
if fixed_type is None:
return self.to(None)
for var_subclass in _var_subclasses[::-1]:
if safe_issubclass(fixed_type, var_subclass.python_types):
return self.to(var_subclass.var_subclass, self._var_type)
if can_use_in_object_var(fixed_type):
return self.to(ObjectVar, self._var_type)
return self
@staticmethod
def _get_setter_name_for_name(
name: str,
) -> str:
"""Get the name of the var's generated setter function.
Args:
name: The name of the var.
Returns:
The name of the setter function.
"""
return constants.SETTER_PREFIX + name
def _get_setter(self, name: str) -> Callable[[BaseState, Any], None]:
"""Get the var's setter function.
Args:
name: The name of the var.
Returns:
A function that that creates a setter for the var.
"""
setter_name = Var._get_setter_name_for_name(name)
def setter(state: Any, value: Any):
"""Get the setter for the var.
Args:
state: The state within which we add the setter function.
value: The value to set.
"""
if self._var_type in [int, float]:
try:
value = self._var_type(value)
setattr(state, name, value)
except ValueError:
console.debug(
f"{type(state).__name__}.{self._js_expr}: Failed conversion of {value!s} to '{self._var_type.__name__}'. Value not set.",
)
else:
setattr(state, name, value)
setter.__annotations__["value"] = self._var_type
setter.__qualname__ = setter_name
return setter
def _var_set_state(self, state: type[BaseState] | str) -> Self:
"""Set the state of the var.
Args:
state: The state to set.
Returns:
The var with the state set.
"""
formatted_state_name = (
state