types.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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 is_none(cls: GenericType) -> bool:
  142. """Check if a class is None.
  143. Args:
  144. cls: The class to check.
  145. Returns:
  146. Whether the class is None.
  147. """
  148. return cls is type(None) or cls is None
  149. @lru_cache()
  150. def is_union(cls: GenericType) -> bool:
  151. """Check if a class is a Union.
  152. Args:
  153. cls: The class to check.
  154. Returns:
  155. Whether the class is a Union.
  156. """
  157. return get_origin(cls) in UnionTypes
  158. @lru_cache()
  159. def is_literal(cls: GenericType) -> bool:
  160. """Check if a class is a Literal.
  161. Args:
  162. cls: The class to check.
  163. Returns:
  164. Whether the class is a literal.
  165. """
  166. return get_origin(cls) is Literal
  167. def has_args(cls) -> bool:
  168. """Check if the class has generic parameters.
  169. Args:
  170. cls: The class to check.
  171. Returns:
  172. Whether the class has generic
  173. """
  174. if get_args(cls):
  175. return True
  176. # Check if the class inherits from a generic class (using __orig_bases__)
  177. if hasattr(cls, "__orig_bases__"):
  178. for base in cls.__orig_bases__:
  179. if get_args(base):
  180. return True
  181. return False
  182. def is_optional(cls: GenericType) -> bool:
  183. """Check if a class is an Optional.
  184. Args:
  185. cls: The class to check.
  186. Returns:
  187. Whether the class is an Optional.
  188. """
  189. return is_union(cls) and type(None) in get_args(cls)
  190. def get_property_hint(attr: Any | None) -> GenericType | None:
  191. """Check if an attribute is a property and return its type hint.
  192. Args:
  193. attr: The descriptor to check.
  194. Returns:
  195. The type hint of the property, if it is a property, else None.
  196. """
  197. if not isinstance(attr, (property, hybrid_property)):
  198. return None
  199. hints = get_type_hints(attr.fget)
  200. return hints.get("return", None)
  201. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  202. """Check if an attribute can be accessed on the cls and return its type.
  203. Supports pydantic models, unions, and annotated attributes on rx.Model.
  204. Args:
  205. cls: The class to check.
  206. name: The name of the attribute to check.
  207. Returns:
  208. The type of the attribute, if accessible, or None
  209. """
  210. from reflex.model import Model
  211. try:
  212. attr = getattr(cls, name, None)
  213. except NotImplementedError:
  214. attr = None
  215. if hint := get_property_hint(attr):
  216. return hint
  217. if (
  218. hasattr(cls, "__fields__")
  219. and name in cls.__fields__
  220. and hasattr(cls.__fields__[name], "outer_type_")
  221. ):
  222. # pydantic models
  223. field = cls.__fields__[name]
  224. type_ = field.outer_type_
  225. if isinstance(type_, ModelField):
  226. type_ = type_.type_
  227. if not field.required and field.default is None:
  228. # Ensure frontend uses null coalescing when accessing.
  229. type_ = Optional[type_]
  230. return type_
  231. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  232. insp = sqlalchemy.inspect(cls)
  233. if name in insp.columns:
  234. # check for list types
  235. column = insp.columns[name]
  236. column_type = column.type
  237. try:
  238. type_ = insp.columns[name].type.python_type
  239. except NotImplementedError:
  240. type_ = None
  241. if type_ is not None:
  242. if hasattr(column_type, "item_type"):
  243. try:
  244. item_type = column_type.item_type.python_type # type: ignore
  245. except NotImplementedError:
  246. item_type = None
  247. if item_type is not None:
  248. if type_ in PrimitiveToAnnotation:
  249. type_ = PrimitiveToAnnotation[type_] # type: ignore
  250. type_ = type_[item_type] # type: ignore
  251. if column.nullable:
  252. type_ = Optional[type_]
  253. return type_
  254. if name in insp.all_orm_descriptors:
  255. descriptor = insp.all_orm_descriptors[name]
  256. if hint := get_property_hint(descriptor):
  257. return hint
  258. if isinstance(descriptor, QueryableAttribute):
  259. prop = descriptor.property
  260. if isinstance(prop, Relationship):
  261. type_ = prop.mapper.class_
  262. # TODO: check for nullable?
  263. type_ = List[type_] if prop.uselist else Optional[type_]
  264. return type_
  265. if isinstance(attr, AssociationProxyInstance):
  266. return List[
  267. get_attribute_access_type(
  268. attr.target_class,
  269. attr.remote_attr.key, # type: ignore[attr-defined]
  270. )
  271. ]
  272. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  273. # Check in the annotations directly (for sqlmodel.Relationship)
  274. hints = get_type_hints(cls)
  275. if name in hints:
  276. type_ = hints[name]
  277. type_origin = get_origin(type_)
  278. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  279. return get_args(type_)[0] # SQLAlchemy v2
  280. if isinstance(type_, ModelField):
  281. return type_.type_ # SQLAlchemy v1.4
  282. return type_
  283. elif is_union(cls):
  284. # Check in each arg of the annotation.
  285. for arg in get_args(cls):
  286. type_ = get_attribute_access_type(arg, name)
  287. if type_ is not None:
  288. # Return the first attribute type that is accessible.
  289. return type_
  290. elif isinstance(cls, type):
  291. # Bare class
  292. if sys.version_info >= (3, 10):
  293. exceptions = NameError
  294. else:
  295. exceptions = (NameError, TypeError)
  296. try:
  297. hints = get_type_hints(cls)
  298. if name in hints:
  299. return hints[name]
  300. except exceptions as e:
  301. console.warn(f"Failed to resolve ForwardRefs for {cls}.{name} due to {e}")
  302. pass
  303. return None # Attribute is not accessible.
  304. @lru_cache()
  305. def get_base_class(cls: GenericType) -> Type:
  306. """Get the base class of a class.
  307. Args:
  308. cls: The class.
  309. Returns:
  310. The base class of the class.
  311. Raises:
  312. TypeError: If a literal has multiple types.
  313. """
  314. if is_literal(cls):
  315. # only literals of the same type are supported.
  316. arg_type = type(get_args(cls)[0])
  317. if not all(type(arg) is arg_type for arg in get_args(cls)):
  318. raise TypeError("only literals of the same type are supported")
  319. return type(get_args(cls)[0])
  320. if is_union(cls):
  321. return tuple(get_base_class(arg) for arg in get_args(cls))
  322. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  323. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  324. """Check if the breakpoints instance satisfies the typing.
  325. Args:
  326. cls_check: The class to check against.
  327. instance: The instance to check.
  328. Returns:
  329. Whether the breakpoints instance satisfies the typing.
  330. """
  331. cls_check_base = get_base_class(cls_check)
  332. if cls_check_base == Breakpoints:
  333. _, expected_type = get_args(cls_check)
  334. if is_literal(expected_type):
  335. for value in instance.values():
  336. if not isinstance(value, str) or value not in get_args(expected_type):
  337. return False
  338. return True
  339. elif isinstance(cls_check_base, tuple):
  340. # union type, so check all types
  341. return any(
  342. _breakpoints_satisfies_typing(type_to_check, instance)
  343. for type_to_check in get_args(cls_check)
  344. )
  345. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  346. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  347. return False
  348. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  349. """Check if a class is a subclass of another class.
  350. Args:
  351. cls: The class to check.
  352. cls_check: The class to check against.
  353. instance: An instance of cls to aid in checking generics.
  354. Returns:
  355. Whether the class is a subclass of the other class.
  356. Raises:
  357. TypeError: If the base class is not valid for issubclass.
  358. """
  359. # Special check for Any.
  360. if cls_check == Any:
  361. return True
  362. if cls in [Any, Callable, None]:
  363. return False
  364. # Get the base classes.
  365. cls_base = get_base_class(cls)
  366. cls_check_base = get_base_class(cls_check)
  367. # The class we're checking should not be a union.
  368. if isinstance(cls_base, tuple):
  369. return False
  370. # Check that fields of breakpoints match the expected values.
  371. if isinstance(instance, Breakpoints):
  372. return _breakpoints_satisfies_typing(cls_check, instance)
  373. # Check if the types match.
  374. try:
  375. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  376. except TypeError as te:
  377. # These errors typically arise from bad annotations and are hard to
  378. # debug without knowing the type that we tried to compare.
  379. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  380. def _isinstance(obj: Any, cls: GenericType) -> bool:
  381. """Check if an object is an instance of a class.
  382. Args:
  383. obj: The object to check.
  384. cls: The class to check against.
  385. Returns:
  386. Whether the object is an instance of the class.
  387. """
  388. return isinstance(obj, get_base_class(cls))
  389. def is_dataframe(value: Type) -> bool:
  390. """Check if the given value is a dataframe.
  391. Args:
  392. value: The value to check.
  393. Returns:
  394. Whether the value is a dataframe.
  395. """
  396. if is_generic_alias(value) or value == Any:
  397. return False
  398. return value.__name__ == "DataFrame"
  399. def is_valid_var_type(type_: Type) -> bool:
  400. """Check if the given type is a valid prop type.
  401. Args:
  402. type_: The type to check.
  403. Returns:
  404. Whether the type is a valid prop type.
  405. """
  406. from reflex.utils import serializers
  407. if is_union(type_):
  408. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  409. return (
  410. _issubclass(type_, StateVar)
  411. or serializers.has_serializer(type_)
  412. or dataclasses.is_dataclass(type_)
  413. )
  414. def is_backend_base_variable(name: str, cls: Type) -> bool:
  415. """Check if this variable name correspond to a backend variable.
  416. Args:
  417. name: The name of the variable to check
  418. cls: The class of the variable to check
  419. Returns:
  420. bool: The result of the check
  421. """
  422. if name in RESERVED_BACKEND_VAR_NAMES:
  423. return False
  424. if not name.startswith("_"):
  425. return False
  426. if name.startswith("__"):
  427. return False
  428. if name.startswith(f"_{cls.__name__}__"):
  429. return False
  430. # Extract the namespace of the original module if defined (dynamic substates).
  431. if callable(getattr(cls, "_get_type_hints", None)):
  432. hints = cls._get_type_hints()
  433. else:
  434. hints = get_type_hints(cls)
  435. if name in hints:
  436. hint = get_origin(hints[name])
  437. if hint == ClassVar:
  438. return False
  439. if name in cls.inherited_backend_vars:
  440. return False
  441. from reflex.vars.base import is_computed_var
  442. if name in cls.__dict__:
  443. value = cls.__dict__[name]
  444. if type(value) is classmethod:
  445. return False
  446. if callable(value):
  447. return False
  448. if isinstance(
  449. value,
  450. (
  451. types.FunctionType,
  452. property,
  453. cached_property,
  454. ),
  455. ) or is_computed_var(value):
  456. return False
  457. return True
  458. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  459. """Check that a value type is found in a list of allowed types.
  460. Args:
  461. value_type: Type of value.
  462. allowed_types: Iterable of allowed types.
  463. Returns:
  464. If the type is found in the allowed types.
  465. """
  466. return get_base_class(value_type) in allowed_types
  467. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  468. """Check that a prop value is in a list of allowed types.
  469. Does the check in a way that works regardless if it's a raw value or a state Var.
  470. Args:
  471. prop: The prop to check.
  472. allowed_types: The list of allowed types.
  473. Returns:
  474. If the prop type match one of the allowed_types.
  475. """
  476. from reflex.vars import Var
  477. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  478. return type_ in allowed_types
  479. def is_encoded_fstring(value) -> bool:
  480. """Check if a value is an encoded Var f-string.
  481. Args:
  482. value: The value string to check.
  483. Returns:
  484. Whether the value is an f-string
  485. """
  486. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  487. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  488. """Check that a value is a valid literal.
  489. Args:
  490. key: The prop name.
  491. value: The prop value to validate.
  492. expected_type: The expected type(literal type).
  493. comp_name: Name of the component.
  494. Raises:
  495. ValueError: When the value is not a valid literal.
  496. """
  497. from reflex.vars import Var
  498. if (
  499. is_literal(expected_type)
  500. and not isinstance(value, Var) # validating vars is not supported yet.
  501. and not is_encoded_fstring(value) # f-strings are not supported.
  502. and value not in expected_type.__args__
  503. ):
  504. allowed_values = expected_type.__args__
  505. if value not in allowed_values:
  506. allowed_value_str = ",".join(
  507. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  508. )
  509. value_str = f"'{value}'" if isinstance(value, str) else value
  510. raise ValueError(
  511. f"prop value for {str(key)} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  512. )
  513. def validate_parameter_literals(func):
  514. """Decorator to check that the arguments passed to a function
  515. correspond to the correct function parameter if it (the parameter)
  516. is a literal type.
  517. Args:
  518. func: The function to validate.
  519. Returns:
  520. The wrapper function.
  521. """
  522. @wraps(func)
  523. def wrapper(*args, **kwargs):
  524. func_params = list(inspect.signature(func).parameters.items())
  525. annotations = {param[0]: param[1].annotation for param in func_params}
  526. # validate args
  527. for param, arg in zip(annotations, args):
  528. if annotations[param] is inspect.Parameter.empty:
  529. continue
  530. validate_literal(param, arg, annotations[param], func.__name__)
  531. # validate kwargs.
  532. for key, value in kwargs.items():
  533. annotation = annotations.get(key)
  534. if not annotation or annotation is inspect.Parameter.empty:
  535. continue
  536. validate_literal(key, value, annotation, func.__name__)
  537. return func(*args, **kwargs)
  538. return wrapper
  539. # Store this here for performance.
  540. StateBases = get_base_class(StateVar)
  541. StateIterBases = get_base_class(StateIterVar)