-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathbase.py
More file actions
3975 lines (3167 loc) ยท 121 KB
/
Copy pathbase.py
File metadata and controls
3975 lines (3167 loc) ยท 121 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,
_validation_depth,
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]] = []
@functools.cache
def _var_subclass_for_conversion(python_type: GenericType) -> VarSubclassEntry | None:
"""Find the registry entry ``Var.to`` maps a python type to.
Later-registered entries take priority, matching the reversed scan the
cache replaces. The registry only grows at import time; registration
clears this cache (see ``Var.__init_subclass__``).
Args:
python_type: The (origin-normalized) python type to look up.
Returns:
The matching entry, or ``None`` if no entry matches.
"""
for var_subclass in reversed(_var_subclasses):
if python_type in var_subclass.python_types or safe_issubclass(
python_type, var_subclass.python_types
):
return var_subclass
return None
@functools.cache
def _var_subclass_matching_python_types(
python_types: tuple[GenericType, ...],
) -> VarSubclassEntry | None:
"""Find the registry entry whose python types cover all ``python_types``.
Used by ``Var.guess_type`` with the (origin-normalized) inner types of
the var type โ a 1-tuple for plain types, the union members otherwise.
Later-registered entries take priority; registration clears this cache.
Args:
python_types: The python types that must all match one entry.
Returns:
The matching entry, or ``None`` if no entry matches.
"""
for var_subclass in reversed(_var_subclasses):
if all(
safe_issubclass(python_type, var_subclass.python_types)
for python_type in python_types
):
return var_subclass
return None
@functools.cache
def _var_subclass_for_var_output(output: type) -> VarSubclassEntry | None:
"""Find the registry entry for a ``Var``-subclass conversion target.
Later-registered entries take priority; registration clears this cache.
Args:
output: The ``Var`` subclass passed to ``Var.to``.
Returns:
The matching entry, or ``None`` if no entry matches.
"""
for var_subclass in reversed(_var_subclasses):
if safe_issubclass(output, var_subclass.var_subclass):
return var_subclass
return None
def _clear_var_subclass_lookup_caches() -> None:
"""Drop cached registry lookups after a new Var subclass registers."""
_var_subclass_for_conversion.cache_clear()
_var_subclass_matching_python_types.cache_clear()
_var_subclass_for_var_output.cache_clear()
def _register_var_subclass_entry(entry: VarSubclassEntry) -> None:
"""Register a Var subclass entry and invalidate cached lookups.
Every append to ``_var_subclasses`` must go through here โ including
manual registrations like ``ReflexURLVar`` โ since a bare append would
leave previously cached lookups returning stale results for types the
new entry claims.
Args:
entry: The entry to append to the registry.
"""
_var_subclasses.append(entry)
_clear_var_subclass_lookup_caches()
_AppWrap = TypeVar("_AppWrap", bound="BaseComponent")
def insert_app_wraps(
target: dict[tuple[int, str], _AppWrap],
sources: Iterable[tuple[int, _AppWrap]],
*,
existing: Mapping[tuple[int, str], _AppWrap] | None = None,
) -> None:
"""Merge app-wrap requests into ``target`` keyed by ``(priority, tag)``.
App wraps model a set of required wrapper roles: at most one wrapper per
``(priority, tag)``. Requests resolving to an equal wrapper are deduped;
two different wrappers claiming one role is a conflict and raises. This is
the single place that rule lives, shared by ``VarData.merge`` (within one
Var) and the compiler's page-wide collection.
Args:
target: Registry that receives newly seen wraps.
sources: ``(priority, wrapper)`` requests to merge in.
existing: Already-committed wraps to dedupe against without writing,
letting callers collect only the wraps they newly contribute.
Raises:
ReflexError: If two different wrappers claim one ``(priority, tag)``.
"""
for priority, wrapper in sources:
key = (priority, wrapper.tag or type(wrapper).__name__)
seen = existing.get(key) if existing is not None else None
if seen is None:
seen = target.get(key)
if seen is not None:
if seen != wrapper:
msg = (
f"Conflicting app wraps for {key!r}: two different "
"components claim the same (priority, tag) slot."
)
raise exceptions.ReflexError(msg)
continue
target[key] = wrapper
@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)
# App-level wrapper components this var requires when used (priority, component).
# Higher priority wraps further out, matching Component._get_app_wrap_components semantics.
app_wraps: tuple[tuple[int, BaseComponent], ...] = 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,
app_wraps: Iterable[tuple[int, BaseComponent]] | 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.
app_wraps: App-level wrapper components this var requires when used.
"""
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, "app_wraps", tuple(app_wraps 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, "app_wraps", merged_var_data.app_wraps)
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
)
app_wraps: dict[tuple[int, str], BaseComponent] = {}
for var_data in all_var_datas:
insert_app_wraps(app_wraps, var_data.app_wraps)
return VarData(
state=state,
field_name=field_name,
imports=imports_,
hooks=hooks,
deps=deps,
position=position,
components=components,
app_wraps=tuple(
(priority, wrapper) for (priority, _tag), wrapper in app_wraps.items()
),
)
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.app_wraps
)
def _identity_key(self) -> tuple:
"""Return a hashable key for ``__eq__`` and ``__hash__``.
``components`` and ``app_wraps`` hold ``BaseComponent`` instances whose
``__eq__`` override drops the default hash. Use component identity for
embedded components because they can contribute hooks/imports, and use
the compiler's app-wrap registry key for wrappers so fresh provider
instances with the same role still compare equal. App wraps are a set
of required roles, so a ``frozenset`` keeps identity insensitive to the
order vars happened to merge in (``a + b`` and ``b + a`` stay equal).
Returns:
A hashable tuple uniquely identifying this VarData.
"""
return (
self.state,
self.field_name,
self.imports,
self.hooks,
self.deps,
self.position,
tuple(id(component) for component in self.components),
frozenset(
(priority, component.tag or type(component).__name__)
for priority, component in self.app_wraps
),
)
def __eq__(self, other: object) -> bool:
"""Compare two VarData by render-time identity.
Args:
other: The value to compare against.
Returns:
True if ``other`` is a VarData with matching render-time fields.
"""
if not isinstance(other, VarData):
return NotImplemented
return self._identity_key() == other._identity_key()
def __hash__(self) -> int:
"""Hash consistent with ``__eq__``.
Returns:
A hash over render-time fields and hashable component metadata.
"""
return hash(self._identity_key())
@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.
"""
# Lazy import: state_context imports VarData from this module.
from reflex_base.components.state_context import get_event_app_wraps
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")],
},
# State Vars read ``StateContexts``/``EventLoopContext``, so the
# providers must enclose every component that uses them.
app_wraps=get_event_app_wraps(),
)
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
_register_var_subclass_entry(
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.
"""
# Operands of a running ``var_operation`` body interpolate as their
# raw JS expression: their VarData flows through the operation's
# ``_args``, so the tag round-trip (and its permanent ``_global_vars``
# entry) is pure overhead there. See ``var_operation``.
if self.__dict__.get("_format_without_tagging"):
return str(self)
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.