Skip to content

Commit 4c4c59b

Browse files
authored
convert event return types to type hints (#4331)
1 parent 2ee2d52 commit 4c4c59b

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

reflex/state.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import json
1212
import pickle
1313
import sys
14+
import typing
1415
import uuid
1516
from abc import ABC, abstractmethod
1617
from collections import defaultdict
@@ -90,7 +91,13 @@
9091
)
9192
from reflex.utils.exec import is_testing_env
9293
from reflex.utils.serializers import serializer
93-
from reflex.utils.types import _isinstance, get_origin, override
94+
from reflex.utils.types import (
95+
_isinstance,
96+
get_origin,
97+
is_union,
98+
override,
99+
value_inside_optional,
100+
)
94101
from reflex.vars import VarData
95102

96103
if TYPE_CHECKING:
@@ -1713,6 +1720,35 @@ async def _process_event(
17131720
# Get the function to process the event.
17141721
fn = functools.partial(handler.fn, state)
17151722

1723+
try:
1724+
type_hints = typing.get_type_hints(handler.fn)
1725+
except Exception:
1726+
type_hints = {}
1727+
1728+
for arg, value in list(payload.items()):
1729+
hinted_args = type_hints.get(arg, Any)
1730+
if hinted_args is Any:
1731+
continue
1732+
if is_union(hinted_args):
1733+
if value is None:
1734+
continue
1735+
hinted_args = value_inside_optional(hinted_args)
1736+
if (
1737+
isinstance(value, dict)
1738+
and inspect.isclass(hinted_args)
1739+
and (
1740+
dataclasses.is_dataclass(hinted_args)
1741+
or issubclass(hinted_args, Base)
1742+
)
1743+
):
1744+
payload[arg] = hinted_args(**value)
1745+
if isinstance(value, list) and (hinted_args is set or hinted_args is Set):
1746+
payload[arg] = set(value)
1747+
if isinstance(value, list) and (
1748+
hinted_args is tuple or hinted_args is Tuple
1749+
):
1750+
payload[arg] = tuple(value)
1751+
17161752
# Wrap the function in a try/except block.
17171753
try:
17181754
# Handle async functions.

0 commit comments

Comments
 (0)