types.py 18 KB

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