types.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import inspect
  6. import sys
  7. import types
  8. from functools import cached_property, lru_cache, wraps
  9. from typing import (
  10. TYPE_CHECKING,
  11. Any,
  12. Callable,
  13. ClassVar,
  14. Dict,
  15. Iterable,
  16. List,
  17. Literal,
  18. Optional,
  19. Tuple,
  20. Type,
  21. Union,
  22. _GenericAlias, # type: ignore
  23. get_args,
  24. get_type_hints,
  25. )
  26. from typing import (
  27. get_origin as get_origin_og,
  28. )
  29. import sqlalchemy
  30. import reflex
  31. from reflex.components.core.breakpoints import Breakpoints
  32. try:
  33. from pydantic.v1.fields import ModelField
  34. except ModuleNotFoundError:
  35. from pydantic.fields import ModelField # type: ignore
  36. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  37. from sqlalchemy.ext.hybrid import hybrid_property
  38. from sqlalchemy.orm import (
  39. DeclarativeBase,
  40. Mapped,
  41. QueryableAttribute,
  42. Relationship,
  43. )
  44. from reflex import constants
  45. from reflex.base import Base
  46. from reflex.utils import console
  47. if sys.version_info >= (3, 12):
  48. from typing import override as override
  49. else:
  50. def override(func: Callable) -> Callable:
  51. """Fallback for @override decorator.
  52. Args:
  53. func: The function to decorate.
  54. Returns:
  55. The unmodified function.
  56. """
  57. return func
  58. # Potential GenericAlias types for isinstance checks.
  59. GenericAliasTypes = [_GenericAlias]
  60. with contextlib.suppress(ImportError):
  61. # For newer versions of Python.
  62. from types import GenericAlias # type: ignore
  63. GenericAliasTypes.append(GenericAlias)
  64. with contextlib.suppress(ImportError):
  65. # For older versions of Python.
  66. from typing import _SpecialGenericAlias # type: ignore
  67. GenericAliasTypes.append(_SpecialGenericAlias)
  68. GenericAliasTypes = tuple(GenericAliasTypes)
  69. # Potential Union types for isinstance checks (UnionType added in py3.10).
  70. UnionTypes = (Union, types.UnionType) if hasattr(types, "UnionType") else (Union,)
  71. # Union of generic types.
  72. GenericType = Union[Type, _GenericAlias]
  73. # Valid state var types.
  74. JSONType = {str, int, float, bool}
  75. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  76. StateVar = Union[PrimitiveType, Base, None]
  77. StateIterVar = Union[list, set, tuple]
  78. if TYPE_CHECKING:
  79. from reflex.vars.base import Var
  80. # ArgsSpec = Callable[[Var], list[Var]]
  81. ArgsSpec = (
  82. Callable[[], List[Var]]
  83. | Callable[[Var], List[Var]]
  84. | Callable[[Var, Var], List[Var]]
  85. | Callable[[Var, Var, Var], List[Var]]
  86. | Callable[[Var, Var, Var, Var], List[Var]]
  87. | Callable[[Var, Var, Var, Var, Var], List[Var]]
  88. | Callable[[Var, Var, Var, Var, Var, Var], List[Var]]
  89. | Callable[[Var, Var, Var, Var, Var, Var, Var], List[Var]]
  90. )
  91. else:
  92. ArgsSpec = Callable[..., List[Any]]
  93. PrimitiveToAnnotation = {
  94. list: List,
  95. tuple: Tuple,
  96. dict: Dict,
  97. }
  98. RESERVED_BACKEND_VAR_NAMES = {
  99. "_abc_impl",
  100. "_backend_vars",
  101. "_was_touched",
  102. }
  103. if sys.version_info >= (3, 11):
  104. from typing import Self as Self
  105. else:
  106. from typing_extensions import Self as Self
  107. class Unset:
  108. """A class to represent an unset value.
  109. This is used to differentiate between a value that is not set and a value that is set to None.
  110. """
  111. def __repr__(self) -> str:
  112. """Return the string representation of the class.
  113. Returns:
  114. The string representation of the class.
  115. """
  116. return "Unset"
  117. def __bool__(self) -> bool:
  118. """Return False when the class is used in a boolean context.
  119. Returns:
  120. False
  121. """
  122. return False
  123. @lru_cache()
  124. def get_origin(tp):
  125. """Get the origin of a class.
  126. Args:
  127. tp: The class to get the origin of.
  128. Returns:
  129. The origin of the class.
  130. """
  131. return get_origin_og(tp)
  132. @lru_cache()
  133. def is_generic_alias(cls: GenericType) -> bool:
  134. """Check whether the class is a generic alias.
  135. Args:
  136. cls: The class to check.
  137. Returns:
  138. Whether the class is a generic alias.
  139. """
  140. return isinstance(cls, GenericAliasTypes)
  141. def unionize(*args: GenericType) -> Type:
  142. """Unionize the types.
  143. Args:
  144. args: The types to unionize.
  145. Returns:
  146. The unionized types.
  147. """
  148. if not args:
  149. return Any
  150. if len(args) == 1:
  151. return args[0]
  152. # We are bisecting the args list here to avoid hitting the recursion limit
  153. # In Python versions >= 3.11, we can simply do `return Union[*args]`
  154. midpoint = len(args) // 2
  155. first_half, second_half = args[:midpoint], args[midpoint:]
  156. return Union[unionize(*first_half), unionize(*second_half)]
  157. def is_none(cls: GenericType) -> bool:
  158. """Check if a class is None.
  159. Args:
  160. cls: The class to check.
  161. Returns:
  162. Whether the class is None.
  163. """
  164. return cls is type(None) or cls is None
  165. @lru_cache()
  166. def is_union(cls: GenericType) -> bool:
  167. """Check if a class is a Union.
  168. Args:
  169. cls: The class to check.
  170. Returns:
  171. Whether the class is a Union.
  172. """
  173. return get_origin(cls) in UnionTypes
  174. @lru_cache()
  175. def is_literal(cls: GenericType) -> bool:
  176. """Check if a class is a Literal.
  177. Args:
  178. cls: The class to check.
  179. Returns:
  180. Whether the class is a literal.
  181. """
  182. return get_origin(cls) is Literal
  183. def has_args(cls) -> bool:
  184. """Check if the class has generic parameters.
  185. Args:
  186. cls: The class to check.
  187. Returns:
  188. Whether the class has generic
  189. """
  190. if get_args(cls):
  191. return True
  192. # Check if the class inherits from a generic class (using __orig_bases__)
  193. if hasattr(cls, "__orig_bases__"):
  194. for base in cls.__orig_bases__:
  195. if get_args(base):
  196. return True
  197. return False
  198. def is_optional(cls: GenericType) -> bool:
  199. """Check if a class is an Optional.
  200. Args:
  201. cls: The class to check.
  202. Returns:
  203. Whether the class is an Optional.
  204. """
  205. return is_union(cls) and type(None) in get_args(cls)
  206. def get_property_hint(attr: Any | None) -> GenericType | None:
  207. """Check if an attribute is a property and return its type hint.
  208. Args:
  209. attr: The descriptor to check.
  210. Returns:
  211. The type hint of the property, if it is a property, else None.
  212. """
  213. if not isinstance(attr, (property, hybrid_property)):
  214. return None
  215. hints = get_type_hints(attr.fget)
  216. return hints.get("return", None)
  217. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  218. """Check if an attribute can be accessed on the cls and return its type.
  219. Supports pydantic models, unions, and annotated attributes on rx.Model.
  220. Args:
  221. cls: The class to check.
  222. name: The name of the attribute to check.
  223. Returns:
  224. The type of the attribute, if accessible, or None
  225. """
  226. from reflex.model import Model
  227. try:
  228. attr = getattr(cls, name, None)
  229. except NotImplementedError:
  230. attr = None
  231. if hint := get_property_hint(attr):
  232. return hint
  233. if (
  234. hasattr(cls, "__fields__")
  235. and name in cls.__fields__
  236. and hasattr(cls.__fields__[name], "outer_type_")
  237. ):
  238. # pydantic models
  239. field = cls.__fields__[name]
  240. type_ = field.outer_type_
  241. if isinstance(type_, ModelField):
  242. type_ = type_.type_
  243. if not field.required and field.default is None:
  244. # Ensure frontend uses null coalescing when accessing.
  245. type_ = Optional[type_]
  246. return type_
  247. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  248. insp = sqlalchemy.inspect(cls)
  249. if name in insp.columns:
  250. # check for list types
  251. column = insp.columns[name]
  252. column_type = column.type
  253. try:
  254. type_ = insp.columns[name].type.python_type
  255. except NotImplementedError:
  256. type_ = None
  257. if type_ is not None:
  258. if hasattr(column_type, "item_type"):
  259. try:
  260. item_type = column_type.item_type.python_type # type: ignore
  261. except NotImplementedError:
  262. item_type = None
  263. if item_type is not None:
  264. if type_ in PrimitiveToAnnotation:
  265. type_ = PrimitiveToAnnotation[type_] # type: ignore
  266. type_ = type_[item_type] # type: ignore
  267. if column.nullable:
  268. type_ = Optional[type_]
  269. return type_
  270. if name in insp.all_orm_descriptors:
  271. descriptor = insp.all_orm_descriptors[name]
  272. if hint := get_property_hint(descriptor):
  273. return hint
  274. if isinstance(descriptor, QueryableAttribute):
  275. prop = descriptor.property
  276. if isinstance(prop, Relationship):
  277. type_ = prop.mapper.class_
  278. # TODO: check for nullable?
  279. type_ = List[type_] if prop.uselist else Optional[type_]
  280. return type_
  281. if isinstance(attr, AssociationProxyInstance):
  282. return List[
  283. get_attribute_access_type(
  284. attr.target_class,
  285. attr.remote_attr.key, # type: ignore[attr-defined]
  286. )
  287. ]
  288. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  289. # Check in the annotations directly (for sqlmodel.Relationship)
  290. hints = get_type_hints(cls)
  291. if name in hints:
  292. type_ = hints[name]
  293. type_origin = get_origin(type_)
  294. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  295. return get_args(type_)[0] # SQLAlchemy v2
  296. if isinstance(type_, ModelField):
  297. return type_.type_ # SQLAlchemy v1.4
  298. return type_
  299. elif is_union(cls):
  300. # Check in each arg of the annotation.
  301. return unionize(
  302. *(get_attribute_access_type(arg, name) for arg in get_args(cls))
  303. )
  304. elif isinstance(cls, type):
  305. # Bare class
  306. if sys.version_info >= (3, 10):
  307. exceptions = NameError
  308. else:
  309. exceptions = (NameError, TypeError)
  310. try:
  311. hints = get_type_hints(cls)
  312. if name in hints:
  313. return hints[name]
  314. except exceptions as e:
  315. console.warn(f"Failed to resolve ForwardRefs for {cls}.{name} due to {e}")
  316. pass
  317. return None # Attribute is not accessible.
  318. @lru_cache()
  319. def get_base_class(cls: GenericType) -> Type:
  320. """Get the base class of a class.
  321. Args:
  322. cls: The class.
  323. Returns:
  324. The base class of the class.
  325. Raises:
  326. TypeError: If a literal has multiple types.
  327. """
  328. if is_literal(cls):
  329. # only literals of the same type are supported.
  330. arg_type = type(get_args(cls)[0])
  331. if not all(type(arg) is arg_type for arg in get_args(cls)):
  332. raise TypeError("only literals of the same type are supported")
  333. return type(get_args(cls)[0])
  334. if is_union(cls):
  335. return tuple(get_base_class(arg) for arg in get_args(cls))
  336. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  337. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  338. """Check if the breakpoints instance satisfies the typing.
  339. Args:
  340. cls_check: The class to check against.
  341. instance: The instance to check.
  342. Returns:
  343. Whether the breakpoints instance satisfies the typing.
  344. """
  345. cls_check_base = get_base_class(cls_check)
  346. if cls_check_base == Breakpoints:
  347. _, expected_type = get_args(cls_check)
  348. if is_literal(expected_type):
  349. for value in instance.values():
  350. if not isinstance(value, str) or value not in get_args(expected_type):
  351. return False
  352. return True
  353. elif isinstance(cls_check_base, tuple):
  354. # union type, so check all types
  355. return any(
  356. _breakpoints_satisfies_typing(type_to_check, instance)
  357. for type_to_check in get_args(cls_check)
  358. )
  359. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  360. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  361. return False
  362. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  363. """Check if a class is a subclass of another class.
  364. Args:
  365. cls: The class to check.
  366. cls_check: The class to check against.
  367. instance: An instance of cls to aid in checking generics.
  368. Returns:
  369. Whether the class is a subclass of the other class.
  370. Raises:
  371. TypeError: If the base class is not valid for issubclass.
  372. """
  373. # Special check for Any.
  374. if cls_check == Any:
  375. return True
  376. if cls in [Any, Callable, None]:
  377. return False
  378. # Get the base classes.
  379. cls_base = get_base_class(cls)
  380. cls_check_base = get_base_class(cls_check)
  381. # The class we're checking should not be a union.
  382. if isinstance(cls_base, tuple):
  383. return False
  384. # Check that fields of breakpoints match the expected values.
  385. if isinstance(instance, Breakpoints):
  386. return _breakpoints_satisfies_typing(cls_check, instance)
  387. # Check if the types match.
  388. try:
  389. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  390. except TypeError as te:
  391. # These errors typically arise from bad annotations and are hard to
  392. # debug without knowing the type that we tried to compare.
  393. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  394. def _isinstance(obj: Any, cls: GenericType) -> bool:
  395. """Check if an object is an instance of a class.
  396. Args:
  397. obj: The object to check.
  398. cls: The class to check against.
  399. Returns:
  400. Whether the object is an instance of the class.
  401. """
  402. return isinstance(obj, get_base_class(cls))
  403. def is_dataframe(value: Type) -> bool:
  404. """Check if the given value is a dataframe.
  405. Args:
  406. value: The value to check.
  407. Returns:
  408. Whether the value is a dataframe.
  409. """
  410. if is_generic_alias(value) or value == Any:
  411. return False
  412. return value.__name__ == "DataFrame"
  413. def is_valid_var_type(type_: Type) -> bool:
  414. """Check if the given type is a valid prop type.
  415. Args:
  416. type_: The type to check.
  417. Returns:
  418. Whether the type is a valid prop type.
  419. """
  420. from reflex.utils import serializers
  421. if is_union(type_):
  422. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  423. return (
  424. _issubclass(type_, StateVar)
  425. or serializers.has_serializer(type_)
  426. or dataclasses.is_dataclass(type_)
  427. )
  428. def is_backend_base_variable(name: str, cls: Type) -> bool:
  429. """Check if this variable name correspond to a backend variable.
  430. Args:
  431. name: The name of the variable to check
  432. cls: The class of the variable to check
  433. Returns:
  434. bool: The result of the check
  435. """
  436. if name in RESERVED_BACKEND_VAR_NAMES:
  437. return False
  438. if not name.startswith("_"):
  439. return False
  440. if name.startswith("__"):
  441. return False
  442. if name.startswith(f"_{cls.__name__}__"):
  443. return False
  444. # Extract the namespace of the original module if defined (dynamic substates).
  445. if callable(getattr(cls, "_get_type_hints", None)):
  446. hints = cls._get_type_hints()
  447. else:
  448. hints = get_type_hints(cls)
  449. if name in hints:
  450. hint = get_origin(hints[name])
  451. if hint == ClassVar:
  452. return False
  453. if name in cls.inherited_backend_vars:
  454. return False
  455. from reflex.vars.base import is_computed_var
  456. if name in cls.__dict__:
  457. value = cls.__dict__[name]
  458. if type(value) is classmethod:
  459. return False
  460. if callable(value):
  461. return False
  462. if isinstance(
  463. value,
  464. (
  465. types.FunctionType,
  466. property,
  467. cached_property,
  468. ),
  469. ) or is_computed_var(value):
  470. return False
  471. return True
  472. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  473. """Check that a value type is found in a list of allowed types.
  474. Args:
  475. value_type: Type of value.
  476. allowed_types: Iterable of allowed types.
  477. Returns:
  478. If the type is found in the allowed types.
  479. """
  480. return get_base_class(value_type) in allowed_types
  481. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  482. """Check that a prop value is in a list of allowed types.
  483. Does the check in a way that works regardless if it's a raw value or a state Var.
  484. Args:
  485. prop: The prop to check.
  486. allowed_types: The list of allowed types.
  487. Returns:
  488. If the prop type match one of the allowed_types.
  489. """
  490. from reflex.vars import Var
  491. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  492. return type_ in allowed_types
  493. def is_encoded_fstring(value) -> bool:
  494. """Check if a value is an encoded Var f-string.
  495. Args:
  496. value: The value string to check.
  497. Returns:
  498. Whether the value is an f-string
  499. """
  500. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  501. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  502. """Check that a value is a valid literal.
  503. Args:
  504. key: The prop name.
  505. value: The prop value to validate.
  506. expected_type: The expected type(literal type).
  507. comp_name: Name of the component.
  508. Raises:
  509. ValueError: When the value is not a valid literal.
  510. """
  511. from reflex.vars import Var
  512. if (
  513. is_literal(expected_type)
  514. and not isinstance(value, Var) # validating vars is not supported yet.
  515. and not is_encoded_fstring(value) # f-strings are not supported.
  516. and value not in expected_type.__args__
  517. ):
  518. allowed_values = expected_type.__args__
  519. if value not in allowed_values:
  520. allowed_value_str = ",".join(
  521. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  522. )
  523. value_str = f"'{value}'" if isinstance(value, str) else value
  524. raise ValueError(
  525. f"prop value for {str(key)} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  526. )
  527. def validate_parameter_literals(func):
  528. """Decorator to check that the arguments passed to a function
  529. correspond to the correct function parameter if it (the parameter)
  530. is a literal type.
  531. Args:
  532. func: The function to validate.
  533. Returns:
  534. The wrapper function.
  535. """
  536. @wraps(func)
  537. def wrapper(*args, **kwargs):
  538. func_params = list(inspect.signature(func).parameters.items())
  539. annotations = {param[0]: param[1].annotation for param in func_params}
  540. # validate args
  541. for param, arg in zip(annotations, args):
  542. if annotations[param] is inspect.Parameter.empty:
  543. continue
  544. validate_literal(param, arg, annotations[param], func.__name__)
  545. # validate kwargs.
  546. for key, value in kwargs.items():
  547. annotation = annotations.get(key)
  548. if not annotation or annotation is inspect.Parameter.empty:
  549. continue
  550. validate_literal(key, value, annotation, func.__name__)
  551. return func(*args, **kwargs)
  552. return wrapper
  553. # Store this here for performance.
  554. StateBases = get_base_class(StateVar)
  555. StateIterBases = get_base_class(StateIterVar)