-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathmemo.py
More file actions
2085 lines (1689 loc) ยท 73.5 KB
/
Copy pathmemo.py
File metadata and controls
2085 lines (1689 loc) ยท 73.5 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
"""Memo support for vars and components."""
from __future__ import annotations
import dataclasses
import inspect
import sys
from collections.abc import Callable, Mapping, Sequence
from copy import copy
from enum import Enum
from functools import cache, partial, update_wrapper
from types import UnionType
from typing import (
Annotated,
Any,
ClassVar,
Generic,
Protocol,
TypeVar,
Union,
cast,
get_args,
get_origin,
get_type_hints,
overload,
)
from reflex_components_core.base.fragment import Fragment
from reflex_base import constants
from reflex_base.components.component import Component
from reflex_base.components.dynamic import bundled_libraries
from reflex_base.components.memoize_helpers import (
MemoizationStrategy,
get_memoization_strategy,
)
from reflex_base.constants.compiler import (
MemoizationDisposition,
MemoizationMode,
SpecialAttributes,
)
from reflex_base.constants.state import CAMEL_CASE_MEMO_MARKER
from reflex_base.event import EventChain, EventHandler, no_args_event_spec, run_script
from reflex_base.utils import console, format, memo_paths
from reflex_base.utils.imports import ImportVar
from reflex_base.utils.types import safe_issubclass, typehint_issubclass
from reflex_base.vars import VarData
from reflex_base.vars.base import LiteralVar, Var
from reflex_base.vars.function import (
ArgsFunctionOperation,
DestructuredArg,
FunctionStringVar,
FunctionVar,
ReflexCallable,
)
from reflex_base.vars.object import RestProp
# A `Var[Component]` default for memo `children` slots (and any prop typed
# `rx.Var[rx.Component]`), mirroring `EMPTY_VAR_STR` / `EMPTY_VAR_INT`. It lives
# here rather than in ``component.py`` because materializing a component var
# eagerly imports ``Bare`` (and thus ``reflex_base.environment``); defining it
# in the always-early ``component.py`` would cycle when ``environment`` is the
# entry point. ``memo.py`` is imported lazily, after ``environment`` is ready.
EMPTY_VAR_COMPONENT: Var[Component] = LiteralVar.create(Component.create())
# The default JS wrapper applied to a compiled component memo's function
# definition: React's ``memo``, carrying its own import. ``@rx.memo`` accepts a
# ``wrapper=`` override to swap it for another helper, or ``None`` to export
# the bare function component.
DEFAULT_MEMO_WRAPPER: FunctionVar = FunctionStringVar.create(
"memo",
_var_data=VarData(imports={"react": [ImportVar(tag="memo")]}),
)
# Base ``Component`` props a memo accepts without an ``rx.RestProp`` (with a
# deprecation warning). Only ``key`` qualifies: React consumes it at the
# reconciliation layer, so it takes effect on the rendered element even though
# the compiled memo function destructures only its declared params. The legacy
# custom-component use case this restores is setting ``key`` under ``rx.foreach``.
#
# Other base props (``id``, ``class_name``, ``style``, ``custom_attrs``,
# ``ref``) are deliberately NOT forwardable: without a ``RestProp`` the memo
# function emits no ``...rest`` spread, so they would be silently dropped rather
# than reaching the root. They raise like any unknown prop, and the error points
# at ``rx.RestProp`` โ which compiles to a ``...rest`` spread that genuinely
# forwards them.
_FORWARDABLE_BASE_PROPS: frozenset[str] = frozenset({"key"})
class MemoParamKind(str, Enum):
"""The role a memo parameter plays in the compiled component.
Each kind owns its full behavior โ annotation classification, call-site
validation, placeholder construction, runtime binding, and JS signature
emission โ via the per-kind :class:`_MemoParamSpec` instance in
:data:`_SPECS`. Adding a new kind means one new entry in :data:`_SPECS`
and one extra step in :data:`_CLASSIFICATION_ORDER`; the rest of the
module learns nothing else about the new kind.
"""
VALUE = "value"
CHILDREN = "children"
REST = "rest"
EVENT_TRIGGER = "event_trigger"
@dataclasses.dataclass(frozen=True, slots=True, kw_only=True)
class MemoParam:
"""Metadata about an analyzed memo parameter."""
name: str
kind: MemoParamKind
annotation: Any
parameter_kind: inspect._ParameterKind
js_prop_name: str
placeholder_name: str
kind_data: Any = None
default: Any = inspect.Parameter.empty
@property
def spec(self) -> _MemoParamSpec:
"""The per-kind behavior bundle for this parameter."""
return _SPECS[self.kind]
def make_placeholder(self) -> Any:
"""Build the value passed to the memo function during analysis.
Returns:
The placeholder value (a ``Var``, ``RestProp``, or plain callable).
"""
return self.spec.make_placeholder(self)
def bind_call_value(self, binding: _MemoCallBinding) -> None:
"""Route a user-provided value to props/event_triggers at instantiation.
Args:
binding: The call-site routing accumulator.
"""
self.spec.bind_call_value(self, binding)
def signature_field(self) -> str | None:
"""The destructured JSX signature entry, or ``None`` if emitted elsewhere.
Returns:
The destructured field (e.g. ``"event:eventRxMemo"``), or ``None``
when this kind is emitted out-of-band by the compiler.
"""
return self.spec.signature_field(self)
@dataclasses.dataclass(frozen=True, slots=True)
class _MemoParamSpec:
"""The role-owned behavior for one :class:`MemoParamKind`.
Hooks (in classification + lifecycle order):
``classify``: ``(annotation, param_name) -> (matches, kind_data)``.
Returns whether the annotation belongs to this kind, plus any
kind-specific payload (the args spec for ``EVENT_TRIGGER``).
``validate``: ``(inspect.Parameter, fn_name, for_component) -> None``.
Raise ``TypeError`` for misuses (no defaults on EH, ``children``
naming, rest-on-var-memo, etc.).
``placeholder_name``: choose the destructured JS identifier (Var/EH
use ``camelCase + RxMemo``; children/rest keep the bare name).
``make_placeholder``: build the analysis-time value passed to the memo
body function (a ``Var``, a ``RestProp``, or a plain callable).
``bind_call_value``: at instantiation, pop the user value from kwargs
and route it via ``_MemoCallBinding`` to props or event_triggers.
``signature_field``: the destructured JSX entry, or ``None`` for kinds
emitted out-of-band (REST -> spread; CHILDREN -> hardcoded prefix).
"""
kind: MemoParamKind
classify: Callable[[Any, str], tuple[bool, Any]]
validate: Callable[[inspect.Parameter, str, bool], None]
placeholder_name: Callable[[str, str, bool], str]
make_placeholder: Callable[[MemoParam], Any]
bind_call_value: Callable[[MemoParam, _MemoCallBinding], None]
signature_field: Callable[[MemoParam], str | None]
_BodyT = TypeVar("_BodyT")
class _LazyBody(Generic[_BodyT]):
"""A memo body computed once, on first read.
``@rx.memo`` registers a definition without running the decorated body; the
body is built by ``thunk`` on the first :meth:`get` and cached thereafter,
so decoration has no import-time side effects. A re-entrant read during that
evaluation โ a component memo that instantiates itself via recursive
``rx.foreach`` โ returns the ``placeholder`` instead of recursing. Var memos
never re-enter (recursion resolves through the imported function var), so
they pass no placeholder. Eagerly built definitions use :meth:`ready`.
Not thread-safe: the re-entrancy guard is a plain flag, which is sufficient
because memo bodies are only ever evaluated during single-threaded compile.
"""
__slots__ = ("_busy", "_placeholder", "_ready", "_thunk", "_value")
_value: _BodyT
def __init__(
self, thunk: Callable[[], _BodyT], placeholder: _BodyT | None = None
) -> None:
"""Defer ``thunk`` until first read.
Args:
thunk: Builds and returns the body on first :meth:`get`.
placeholder: Stand-in returned if the body is read while ``thunk``
is still running (the recursive component-memo case).
"""
self._thunk = thunk
self._placeholder = placeholder
self._ready = False
self._busy = False
@classmethod
def ready(cls, value: _BodyT) -> _LazyBody[_BodyT]:
"""Wrap an already-computed body.
Args:
value: The precomputed body.
Returns:
A lazy body that yields ``value`` without running a thunk.
"""
body = cls(lambda: value)
body._value = value
body._ready = True
return body
def get(self) -> _BodyT:
"""Return the body, running and caching ``thunk`` on first read.
Returns:
The cached body, or the placeholder when read mid-evaluation.
Raises:
RuntimeError: If the body re-enters its own evaluation but carries
no placeholder (only component memos re-enter, and they always
provide one โ so this signals a broken invariant, not a missing
body).
"""
if self._ready:
return self._value
if self._busy:
if self._placeholder is None:
msg = "Re-entrant memo body read before its evaluation finished."
raise RuntimeError(msg)
return self._placeholder
self._busy = True
try:
self._value = self._thunk()
self._ready = True
finally:
self._busy = False
return self._value
@dataclasses.dataclass(frozen=True, slots=True)
class MemoDefinition:
"""Base metadata for a memo."""
fn: Callable[..., Any]
python_name: str
params: tuple[MemoParam, ...]
# The Python module that defined this memo. When set, the memo's compiled
# JSX is emitted to a path mirroring that module and the page-side import
# resolves there instead of the per-name ``utils/components/<name>`` path
# used for memos that can't be mirrored. ``kw_only`` so subclasses can keep
# their own required fields.
source_module: str | None = dataclasses.field(default=None, kw_only=True)
@dataclasses.dataclass(frozen=True, slots=True)
class MemoFunctionDefinition(MemoDefinition):
"""A memo that compiles to a JavaScript function."""
_function: _LazyBody[ArgsFunctionOperation]
imported_var: FunctionVar
@property
def function(self) -> ArgsFunctionOperation:
"""The compiled function body, evaluated on first access.
Returns:
The compiled ``ArgsFunctionOperation`` for this memo.
"""
return self._function.get()
@dataclasses.dataclass(frozen=True, slots=True)
class MemoComponentDefinition(MemoDefinition):
"""A memo that compiles to a React component."""
export_name: str
_component: _LazyBody[Component]
# For passthrough wrappers built by the auto-memoize plugin: the
# ``Bare``-wrapped ``{children}`` placeholder used when rendering the memo
# body. The ``component`` keeps its ORIGINAL children so compile-time
# walkers (``Form._get_form_refs`` etc.) can introspect the subtree; the
# compiler swaps to this placeholder only for the JSX render and for
# imports collection, so descendants emit their refs/imports/hooks in the
# page scope rather than being duplicated inside the memo body.
passthrough_hole_child: Component | None = None
# The JS function the compiled function component is wrapped in โ React's
# ``memo`` by default. ``None`` exports the bare function component. The
# wrapper's ``VarData`` supplies its imports, so a custom wrapper brings
# its own and ``None`` pulls in nothing.
wrapper: Var | None = DEFAULT_MEMO_WRAPPER
@property
def component(self) -> Component:
"""The compiled component body, evaluated on first access.
Returns:
The compiled ``Component`` for this memo.
"""
return self._component.get()
class MemoComponent(Component):
"""A rendered instance of a memo component."""
library = f"$/{constants.Dirs.COMPONENTS_PATH}"
_memoization_mode = MemoizationMode(disposition=MemoizationDisposition.NEVER)
# The user-authored component class this wrapper stands in for. Populated
# on the dynamic subclass by ``_get_memo_component_class`` so
# introspection (e.g. compile telemetry) can recover the underlying type
# without parsing the wrapper's auto-generated class name.
_wrapped_component_type: ClassVar[type[Component] | None] = None
def _validate_component_children(self, children: list[Component]) -> None:
"""Skip direct parent/child validation for memo wrapper instances.
Memos wrap an underlying compiled component definition.
The runtime wrapper should not interpose on `_valid_parents` checks for
the authored subtree because the wrapper itself is not the semantic
parent in the user-authored component tree.
Args:
children: The children of the component (ignored).
"""
def _post_init(self, **kwargs):
"""Initialize the memo component.
Args:
**kwargs: The kwargs to pass to the component.
"""
definition = kwargs.pop("memo_definition")
binding = _MemoCallBinding(kwargs)
for param in definition.params:
param.bind_call_value(binding)
has_rest = _get_rest_param(definition.params) is not None
rest_props = binding.take_rest(self.get_fields()) if has_rest else {}
super()._post_init(**binding.build_super_kwargs())
prop_names = binding.finalize(self, rest_props)
object.__setattr__(self, "get_props", lambda: prop_names)
@cache
def _get_memo_component_class(
export_name: str,
wrapped_component_type: type[Component] = Component,
source_module: str | None = None,
) -> type[MemoComponent]:
"""Get the component subclass for a memo export.
Class-level metadata that the compiler reads via ``type(comp)._get_*()``
(notably ``_get_app_wrap_components``, which carries providers like
``UploadFilesProvider`` that must reach the app root) is inherited from
``wrapped_component_type`` so the wrapper is a transparent substitute for
the original in the compile tree.
Args:
export_name: The exported React component name.
wrapped_component_type: The class of the component being memoized.
Defaults to ``Component`` for memos that don't wrap a user
component (e.g. function memos, raw passthroughs).
source_module: The user-app Python module that defined this memo. When
set, the wrapper imports from a path mirroring that module instead
of the per-name ``utils/components/<name>`` path.
Returns:
A cached component subclass with the tag set at class definition time.
"""
# With a source module the memo is grouped into a file mirroring its
# Python module; otherwise each memo gets its own per-file module so Vite
# has distinct module boundaries per memo, enabling code-split by page.
library, symbol = memo_paths.library_and_symbol(source_module, export_name)
attrs: dict[str, Any] = {
"__module__": __name__,
"tag": symbol,
"library": library,
"_wrapped_component_type": wrapped_component_type,
}
if (
wrapped_component_type._get_app_wrap_components
is not Component._get_app_wrap_components
):
attrs["_get_app_wrap_components"] = staticmethod(
wrapped_component_type._get_app_wrap_components
)
return type(
f"MemoComponent_{symbol}",
(MemoComponent,),
attrs,
)
def reset_memo_component_classes() -> None:
"""Clear the cached memo wrapper classes.
Called at the start of each compile so a memo's ``library`` is recomputed
from the current module layout. Without this, a module that switches to a
package (or back) between hot-reload compiles would keep serving the
library specifier resolved on the first compile, pointing pages at an
output path the compiler no longer writes.
"""
_get_memo_component_class.cache_clear()
MEMOS: dict[tuple[str, str | None], MemoDefinition] = {}
def _memo_registry_key(definition: MemoDefinition) -> tuple[str, str | None]:
"""Get the registry key for a memo.
The key pairs the compiled name with the source module: two memos with the
same name in different modules compile to distinct files (and distinct JS
symbols), so they must register as separate entries rather than colliding.
Args:
definition: The memo definition.
Returns:
The ``(name, source_module)`` registry key for the memo.
"""
if isinstance(definition, MemoComponentDefinition):
return definition.export_name, definition.source_module
return definition.python_name, definition.source_module
def _is_memo_reregistration(
existing: MemoDefinition,
definition: MemoDefinition,
) -> bool:
"""Check whether a memo definition replaces the same memo during reload.
Args:
existing: The currently registered memo definition.
definition: The new memo definition being registered.
Returns:
Whether the new definition should replace the existing one.
"""
return (
type(existing) is type(definition)
and existing.python_name == definition.python_name
and existing.fn.__module__ == definition.fn.__module__
and existing.fn.__qualname__ == definition.fn.__qualname__
)
def _register_memo_definition(definition: MemoDefinition) -> None:
"""Register a memo definition.
Args:
definition: The memo definition to register.
Raises:
ValueError: If another memo already compiles to the same exported name.
"""
key = _memo_registry_key(definition)
if (existing := MEMOS.get(key)) is not None and (
not _is_memo_reregistration(existing, definition)
):
msg = (
f"Memo name collision for `{key[0]}`: "
f"`{existing.fn.__module__}.{existing.python_name}` and "
f"`{definition.fn.__module__}.{definition.python_name}` both compile "
"to the same memo name in the same module."
)
raise ValueError(msg)
MEMOS[key] = definition
def _reregister_used_memo(definition: MemoDefinition) -> None:
"""Re-register a used ``@rx.memo`` so a cleared ``MEMOS`` is repopulated from
usage. Passthrough auto-memos (defined in this module) are tracked
separately and stay out of ``MEMOS``.
"""
if definition.fn.__module__ != __name__:
_register_memo_definition(definition)
def materialize_registered_memo_bodies() -> None:
"""Evaluate every registered memo body, until ``MEMOS`` stops growing.
Reading a memo body re-registers any nested ``@rx.memo`` it references (see
:func:`_reregister_used_memo`), so the compiler must do this before it
snapshots ``MEMOS`` โ else a dependency surfaced only while compiling a lazy
var-memo body is left out. Bodies cache, so re-reading one is a no-op.
"""
evaluated: set[tuple[str, str | None]] = set()
while pending := [
(key, definition) for key, definition in MEMOS.items() if key not in evaluated
]:
for key, definition in pending:
evaluated.add(key)
if isinstance(definition, MemoFunctionDefinition):
_ = definition.function
elif isinstance(definition, MemoComponentDefinition):
_ = definition.component
def _annotation_inner_type(annotation: Any) -> Any:
"""Unwrap a Var-like annotation to its inner type.
Args:
annotation: The annotation to unwrap.
Returns:
The inner type for the annotation.
"""
if _is_rest_annotation(annotation):
return dict[str, Any]
annotation = _strip_annotated(annotation)
origin = get_origin(annotation) or annotation
if safe_issubclass(origin, Var) and (args := get_args(annotation)):
return args[0]
return Any
def _strip_annotated(annotation: Any) -> Any:
"""Unwrap ``Annotated[X, ...]`` to ``X``; pass other annotations through.
Args:
annotation: The annotation to unwrap.
Returns:
The inner annotation, or the original if not ``Annotated``.
"""
if get_origin(annotation) is Annotated:
return get_args(annotation)[0]
return annotation
_UNION_ORIGINS = (Union, UnionType)
# Python <=3.10's ``get_type_hints`` rewrites a parameter with a ``= None``
# default into ``Optional[...]``, hiding the real annotation from the param
# classifiers; 3.11 dropped that behavior. Only those versions need the
# ``_strip_optional`` normalization, so newer interpreters skip it entirely
# rather than pay ``get_origin`` per parameter for a problem they don't have.
_GET_TYPE_HINTS_WRAPS_NONE_DEFAULT = sys.version_info < (3, 11)
def _strip_optional(annotation: Any) -> Any:
"""Unwrap ``Optional[X]`` / ``X | None`` down to ``X``.
Restores the annotation the classifiers expect after Python <=3.10's
``get_type_hints`` wraps a ``= None``-defaulted parameter in ``Optional``
(see ``_GET_TYPE_HINTS_WRAPS_NONE_DEFAULT``).
Args:
annotation: The annotation to normalize.
Returns:
The sole non-``None`` member of an ``Optional`` union, else the
annotation unchanged.
"""
if get_origin(annotation) in _UNION_ORIGINS:
non_none = [arg for arg in get_args(annotation) if arg is not type(None)]
if len(non_none) == 1:
return non_none[0]
return annotation
def _is_rest_annotation(annotation: Any) -> bool:
"""Check whether an annotation is a RestProp.
Args:
annotation: The annotation to check.
Returns:
Whether the annotation is a RestProp.
"""
annotation = _strip_annotated(annotation)
origin = get_origin(annotation) or annotation
return isinstance(origin, type) and issubclass(origin, RestProp)
def _is_var_annotation(annotation: Any) -> bool:
"""Check whether an annotation is a Var-like annotation.
Args:
annotation: The annotation to check.
Returns:
Whether the annotation is Var-like.
"""
annotation = _strip_annotated(annotation)
origin = get_origin(annotation) or annotation
return isinstance(origin, type) and issubclass(origin, Var)
def _is_event_handler_annotation(annotation: Any) -> tuple[bool, Any]:
"""Detect ``EventHandler`` / ``EventHandler[spec]`` / ``EventHandler[s1, s2]``.
``EventHandler.__class_getitem__`` returns ``Annotated[EventHandler, spec]`` for a
single spec and ``Annotated[EventHandler, (s1, s2)]`` (a tuple in the single
metadata slot) for multiple specs.
Args:
annotation: The annotation to inspect.
Returns:
``(is_event_handler, args_spec)`` โ ``args_spec`` is ``no_args_event_spec`` for
bare ``EventHandler``, a single spec callable for ``EventHandler[spec]``, or
the tuple of specs for the multi-spec form.
"""
if get_origin(annotation) is Annotated:
inner, *metadata = get_args(annotation)
if isinstance(inner, type) and safe_issubclass(inner, EventHandler):
return True, metadata[0]
return False, None
if isinstance(annotation, type) and safe_issubclass(annotation, EventHandler):
return True, no_args_event_spec
return False, None
def _is_component_annotation(annotation: Any) -> bool:
"""Check whether an annotation is component-like.
Args:
annotation: The annotation to check.
Returns:
Whether the annotation resolves to Component.
"""
annotation = _strip_annotated(annotation)
origin = get_origin(annotation) or annotation
return isinstance(origin, type) and (
safe_issubclass(origin, Component)
or bool(
safe_issubclass(origin, Var)
and (args := get_args(annotation))
and safe_issubclass(args[0], Component)
)
)
def _is_memo_annotation(annotation: Any) -> bool:
"""Check whether an annotation is already a recognized memo annotation.
Recognized annotations are ``rx.Var[...]`` (including ``rx.RestProp``, a
``Var`` subclass) and ``rx.EventHandler[...]``. Anything else is a legacy
bare Python type that the public :func:`memo` decorator coerces into
``rx.Var[...]`` for backwards compatibility.
Args:
annotation: The annotation to check.
Returns:
Whether the annotation is already a valid memo parameter annotation.
"""
return _is_var_annotation(annotation) or _is_event_handler_annotation(annotation)[0]
def _children_annotation_is_valid(annotation: Any) -> bool:
"""Check whether an annotation is valid for children.
Args:
annotation: The annotation to check.
Returns:
Whether the annotation is valid for children.
"""
return _is_var_annotation(annotation) and typehint_issubclass(
_annotation_inner_type(annotation), Component
)
def _get_children_param(params: tuple[MemoParam, ...]) -> MemoParam | None:
return next((p for p in params if p.kind is MemoParamKind.CHILDREN), None)
def _get_rest_param(params: tuple[MemoParam, ...]) -> MemoParam | None:
return next((p for p in params if p.kind is MemoParamKind.REST), None)
def _imported_function_var(
name: str, return_type: Any, source_module: str | None = None
) -> FunctionVar:
"""Create the imported FunctionVar for a memo.
Args:
name: The exported function name.
return_type: The return type of the function.
source_module: The Python module that defined the memo. When set, the
import resolves to the mirrored module file instead of the per-name
``utils/components/<name>`` path.
Returns:
The imported FunctionVar.
"""
library, symbol = memo_paths.library_and_symbol(source_module, name)
return FunctionStringVar.create(
symbol,
_var_type=ReflexCallable[Any, return_type],
_var_data=VarData(imports={library: [ImportVar(tag=symbol)]}),
)
def _component_import_var(name: str, source_module: str | None = None) -> Var:
"""Create the imported component var for a memo component.
Args:
name: The exported component name.
source_module: The Python module that defined the memo. When set, the
import resolves to the mirrored module file instead of the per-name
``utils/components/<name>`` path.
Returns:
The component var.
"""
library, symbol = memo_paths.library_and_symbol(source_module, name)
return Var(
symbol,
_var_type=type[Component],
_var_data=VarData(
imports={
library: [ImportVar(tag=symbol)],
"@emotion/react": [ImportVar(tag="jsx")],
}
),
)
def _validate_var_return_expr(return_expr: Var, func_name: str) -> None:
"""Validate that a var-returning memo can compile safely.
Args:
return_expr: The return expression.
func_name: The function name for error messages.
Raises:
TypeError: If the return expression depends on unsupported features.
"""
var_data = VarData.merge(return_expr._get_all_var_data())
if var_data is None:
return
if var_data.hooks:
msg = (
f"Var-returning `@rx.memo` `{func_name}` cannot depend on hooks. "
"Use a component-returning `@rx.memo` instead."
)
raise TypeError(msg)
if var_data.components:
msg = (
f"Var-returning `@rx.memo` `{func_name}` cannot depend on embedded "
"components, custom code, or dynamic imports. Use a component-returning "
"`@rx.memo` instead."
)
raise TypeError(msg)
for lib in dict(var_data.imports):
if not lib:
continue
if lib.startswith((".", "/", "$/", "http")):
continue
if format.format_library_name(lib) in bundled_libraries:
continue
msg = (
f"Var-returning `@rx.memo` `{func_name}` cannot import `{lib}` because "
"it is not bundled. Use a component-returning `@rx.memo` instead."
)
raise TypeError(msg)
def _rest_placeholder(name: str) -> RestProp:
"""Create the placeholder RestProp.
Args:
name: The JavaScript identifier.
Returns:
The placeholder rest prop.
"""
return RestProp(_js_expr=name, _var_type=dict[str, Any])
def _var_placeholder(name: str, annotation: Any) -> Var:
"""Create a placeholder Var for a memo parameter.
Args:
name: The JavaScript identifier.
annotation: The parameter annotation.
Returns:
The placeholder Var.
"""
return Var(_js_expr=name, _var_type=_annotation_inner_type(annotation)).guess_type()
def _event_handler_placeholder(placeholder_name: str, args_spec: Any) -> Callable:
"""Placeholder callable that compiles calls to the destructured JS prop.
Returned as a plain callable (not an ``EventHandler``) so it flows through
``EventChain.create`` -> ``call_event_fn``, which actually invokes it.
Wrapping in an ``EventHandler`` would skip the function body and bake the
Python function name into the rendered ``ReflexEvent(...)`` payload.
Args:
placeholder_name: The destructured JS prop identifier (e.g. ``eventRxMemo``).
args_spec: The user-declared spec, or a tuple of specs from
``EventHandler[s1, s2]``. Only the first spec shapes the placeholder's
signature; the inner-trigger boundary handles the rest.
Returns:
A plain callable suitable as a memo-function placeholder.
"""
prop_callback = Var(_js_expr=placeholder_name).to(FunctionVar)
primary_spec = args_spec[0] if isinstance(args_spec, tuple) else args_spec
def _placeholder(*args: Any) -> Any:
return run_script(prop_callback.call(*args))
_placeholder.__signature__ = inspect.signature(primary_spec) # pyright: ignore[reportFunctionMemberAccess]
return _placeholder
def _classify_value(annotation: Any, name: str) -> tuple[bool, Any]:
# ``RestProp`` is a ``Var`` subclass, so guard against it here even though
# ``_CLASSIFICATION_ORDER`` already tries REST first โ keeping the classifier
# self-exclusive removes the implicit ordering dependency.
return (
_is_var_annotation(annotation) and not _is_rest_annotation(annotation),
None,
)
def _classify_children(annotation: Any, name: str) -> tuple[bool, Any]:
return (
name == "children" and _children_annotation_is_valid(annotation),
None,
)
def _classify_rest(annotation: Any, name: str) -> tuple[bool, Any]:
return _is_rest_annotation(annotation), None
def _classify_event_trigger(annotation: Any, name: str) -> tuple[bool, Any]:
return _is_event_handler_annotation(annotation)
def _validate_noop(
parameter: inspect.Parameter, fn_name: str, for_component: bool
) -> None:
pass
def _validate_children(
parameter: inspect.Parameter, fn_name: str, for_component: bool
) -> None:
if parameter.name != "children":
msg = (
f"`rx.Var[rx.Component]` parameters in `{fn_name}` must be named "
"`children`."
)
raise TypeError(msg)
def _validate_rest(
parameter: inspect.Parameter, fn_name: str, for_component: bool
) -> None:
if parameter.name == "children":
msg = f"`children` in `{fn_name}` cannot be `rx.RestProp`."
raise TypeError(msg)
def _validate_event_trigger(
parameter: inspect.Parameter, fn_name: str, for_component: bool
) -> None:
if not for_component:
msg = (
f"`rx.EventHandler` parameters are only supported on component-"
f"returning memos. Got `{parameter.name}` in `{fn_name}`."
)
raise TypeError(msg)
if parameter.name == "children":
msg = (
f"`children` in `{fn_name}` cannot be an `rx.EventHandler`; "
"use `rx.Var[rx.Component]`."
)
raise TypeError(msg)
if parameter.default is not inspect.Parameter.empty:
msg = (
f"`rx.EventHandler` parameter `{parameter.name}` in `{fn_name}` "
"must not have a default value."
)
raise TypeError(msg)
def _placeholder_name_value(name: str, js_prop_name: str, for_component: bool) -> str:
return js_prop_name + CAMEL_CASE_MEMO_MARKER if for_component else name
def _placeholder_name_passthrough(
name: str, js_prop_name: str, for_component: bool
) -> str:
return name
def _make_value_placeholder(param: MemoParam) -> Var:
return _var_placeholder(param.placeholder_name, param.annotation)
def _make_rest_placeholder_spec(param: MemoParam) -> RestProp:
return _rest_placeholder(param.placeholder_name)
def _make_event_trigger_placeholder(param: MemoParam) -> Callable[..., Any]:
return _event_handler_placeholder(param.placeholder_name, param.kind_data)
def _bind_value(param: MemoParam, binding: _MemoCallBinding) -> None:
if param.name in binding.raw_kwargs:
binding.add_prop(param.js_prop_name, binding.take(param.name))
def _bind_children(param: MemoParam, binding: _MemoCallBinding) -> None:
pass
def _bind_rest(param: MemoParam, binding: _MemoCallBinding) -> None:
pass
def _bind_event_trigger(param: MemoParam, binding: _MemoCallBinding) -> None:
if param.name in binding.raw_kwargs:
binding.add_event_trigger(
param.js_prop_name, binding.take(param.name), param.kind_data
)
def _signature_destructured(param: MemoParam) -> str:
return f"{param.js_prop_name}:{param.placeholder_name}"
def _signature_none(param: MemoParam) -> None:
return None
_SPECS: dict[MemoParamKind, _MemoParamSpec] = {
MemoParamKind.VALUE: _MemoParamSpec(
kind=MemoParamKind.VALUE,
classify=_classify_value,
validate=_validate_noop,
placeholder_name=_placeholder_name_value,
make_placeholder=_make_value_placeholder,
bind_call_value=_bind_value,
signature_field=_signature_destructured,
),
MemoParamKind.CHILDREN: _MemoParamSpec(
kind=MemoParamKind.CHILDREN,
classify=_classify_children,
validate=_validate_children,
placeholder_name=_placeholder_name_passthrough,
make_placeholder=_make_value_placeholder,
bind_call_value=_bind_children,
signature_field=_signature_none,
),
MemoParamKind.REST: _MemoParamSpec(
kind=MemoParamKind.REST,
classify=_classify_rest,
validate=_validate_rest,
placeholder_name=_placeholder_name_passthrough,
make_placeholder=_make_rest_placeholder_spec,
bind_call_value=_bind_rest,
signature_field=_signature_none,
),
MemoParamKind.EVENT_TRIGGER: _MemoParamSpec(
kind=MemoParamKind.EVENT_TRIGGER,
classify=_classify_event_trigger,
validate=_validate_event_trigger,
placeholder_name=_placeholder_name_value,
make_placeholder=_make_event_trigger_placeholder,