types.py 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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 collections import abc
  9. from functools import cached_property, lru_cache, wraps
  10. from typing import (
  11. TYPE_CHECKING,
  12. Any,
  13. Callable,
  14. ClassVar,
  15. Dict,
  16. FrozenSet,
  17. Iterable,
  18. List,
  19. Literal,
  20. Mapping,
  21. Optional,
  22. Sequence,
  23. Tuple,
  24. Type,
  25. TypeVar,
  26. Union,
  27. _GenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  28. get_args,
  29. get_type_hints,
  30. )
  31. from typing import get_origin as get_origin_og
  32. import sqlalchemy
  33. import typing_extensions
  34. from typing_extensions import is_typeddict
  35. import reflex
  36. from reflex.components.core.breakpoints import Breakpoints
  37. try:
  38. from pydantic.v1.fields import ModelField
  39. except ModuleNotFoundError:
  40. from pydantic.fields import (
  41. ModelField, # pyright: ignore [reportAttributeAccessIssue]
  42. )
  43. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  44. from sqlalchemy.ext.hybrid import hybrid_property
  45. from sqlalchemy.orm import DeclarativeBase, Mapped, QueryableAttribute, Relationship
  46. from reflex import constants
  47. from reflex.base import Base
  48. from reflex.utils import console
  49. if sys.version_info >= (3, 12):
  50. from typing import override as override
  51. else:
  52. def override(func: Callable) -> Callable:
  53. """Fallback for @override decorator.
  54. Args:
  55. func: The function to decorate.
  56. Returns:
  57. The unmodified function.
  58. """
  59. return func
  60. # Potential GenericAlias types for isinstance checks.
  61. _GenericAliasTypes: list[type] = [_GenericAlias]
  62. with contextlib.suppress(ImportError):
  63. # For newer versions of Python.
  64. from types import GenericAlias
  65. _GenericAliasTypes.append(GenericAlias)
  66. with contextlib.suppress(ImportError):
  67. # For older versions of Python.
  68. from typing import (
  69. _SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  70. )
  71. _GenericAliasTypes.append(_SpecialGenericAlias)
  72. GenericAliasTypes = tuple(_GenericAliasTypes)
  73. # Potential Union types for isinstance checks (UnionType added in py3.10).
  74. UnionTypes = (Union, types.UnionType) if hasattr(types, "UnionType") else (Union,)
  75. # Union of generic types.
  76. GenericType = Union[Type, _GenericAlias]
  77. # Valid state var types.
  78. JSONType = {str, int, float, bool}
  79. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  80. PrimitiveTypes = (int, float, bool, str, list, dict, set, tuple)
  81. StateVar = Union[PrimitiveType, Base, None]
  82. StateIterVar = Union[list, set, tuple]
  83. if TYPE_CHECKING:
  84. from reflex.vars.base import Var
  85. ArgsSpec = (
  86. Callable[[], Sequence[Var]]
  87. | Callable[[Var], Sequence[Var]]
  88. | Callable[[Var, Var], Sequence[Var]]
  89. | Callable[[Var, Var, Var], Sequence[Var]]
  90. | Callable[[Var, Var, Var, Var], Sequence[Var]]
  91. | Callable[[Var, Var, Var, Var, Var], Sequence[Var]]
  92. | Callable[[Var, Var, Var, Var, Var, Var], Sequence[Var]]
  93. | Callable[[Var, Var, Var, Var, Var, Var, Var], Sequence[Var]]
  94. )
  95. else:
  96. ArgsSpec = Callable[..., List[Any]]
  97. PrimitiveToAnnotation = {
  98. list: List,
  99. tuple: Tuple,
  100. dict: Dict,
  101. }
  102. RESERVED_BACKEND_VAR_NAMES = {
  103. "_abc_impl",
  104. "_backend_vars",
  105. "_was_touched",
  106. }
  107. if sys.version_info >= (3, 11):
  108. from typing import Self as Self
  109. else:
  110. from typing_extensions import Self as Self
  111. class Unset:
  112. """A class to represent an unset value.
  113. This is used to differentiate between a value that is not set and a value that is set to None.
  114. """
  115. def __repr__(self) -> str:
  116. """Return the string representation of the class.
  117. Returns:
  118. The string representation of the class.
  119. """
  120. return "Unset"
  121. def __bool__(self) -> bool:
  122. """Return False when the class is used in a boolean context.
  123. Returns:
  124. False
  125. """
  126. return False
  127. @lru_cache()
  128. def get_origin(tp: Any):
  129. """Get the origin of a class.
  130. Args:
  131. tp: The class to get the origin of.
  132. Returns:
  133. The origin of the class.
  134. """
  135. return get_origin_og(tp)
  136. @lru_cache()
  137. def is_generic_alias(cls: GenericType) -> bool:
  138. """Check whether the class is a generic alias.
  139. Args:
  140. cls: The class to check.
  141. Returns:
  142. Whether the class is a generic alias.
  143. """
  144. return isinstance(cls, GenericAliasTypes) # pyright: ignore [reportArgumentType]
  145. def unionize(*args: GenericType) -> GenericType:
  146. """Unionize the types.
  147. Args:
  148. args: The types to unionize.
  149. Returns:
  150. The unionized types.
  151. """
  152. if not args:
  153. return Any # pyright: ignore [reportReturnType]
  154. if len(args) == 1:
  155. return args[0]
  156. # We are bisecting the args list here to avoid hitting the recursion limit
  157. # In Python versions >= 3.11, we can simply do `return Union[*args]`
  158. midpoint = len(args) // 2
  159. first_half, second_half = args[:midpoint], args[midpoint:]
  160. return Union[unionize(*first_half), unionize(*second_half)] # pyright: ignore [reportReturnType]
  161. def is_none(cls: GenericType) -> bool:
  162. """Check if a class is None.
  163. Args:
  164. cls: The class to check.
  165. Returns:
  166. Whether the class is None.
  167. """
  168. return cls is type(None) or cls is None
  169. @lru_cache()
  170. def is_union(cls: GenericType) -> bool:
  171. """Check if a class is a Union.
  172. Args:
  173. cls: The class to check.
  174. Returns:
  175. Whether the class is a Union.
  176. """
  177. return get_origin(cls) in UnionTypes
  178. @lru_cache()
  179. def is_literal(cls: GenericType) -> bool:
  180. """Check if a class is a Literal.
  181. Args:
  182. cls: The class to check.
  183. Returns:
  184. Whether the class is a literal.
  185. """
  186. return get_origin(cls) is Literal
  187. def has_args(cls: Type) -> bool:
  188. """Check if the class has generic parameters.
  189. Args:
  190. cls: The class to check.
  191. Returns:
  192. Whether the class has generic
  193. """
  194. if get_args(cls):
  195. return True
  196. # Check if the class inherits from a generic class (using __orig_bases__)
  197. if hasattr(cls, "__orig_bases__"):
  198. for base in cls.__orig_bases__:
  199. if get_args(base):
  200. return True
  201. return False
  202. def is_optional(cls: GenericType) -> bool:
  203. """Check if a class is an Optional.
  204. Args:
  205. cls: The class to check.
  206. Returns:
  207. Whether the class is an Optional.
  208. """
  209. return is_union(cls) and type(None) in get_args(cls)
  210. def value_inside_optional(cls: GenericType) -> GenericType:
  211. """Get the value inside an Optional type or the original type.
  212. Args:
  213. cls: The class to check.
  214. Returns:
  215. The value inside the Optional type or the original type.
  216. """
  217. if is_union(cls) and len(args := get_args(cls)) >= 2 and type(None) in args:
  218. return unionize(*[arg for arg in args if arg is not type(None)])
  219. return cls
  220. def get_property_hint(attr: Any | None) -> GenericType | None:
  221. """Check if an attribute is a property and return its type hint.
  222. Args:
  223. attr: The descriptor to check.
  224. Returns:
  225. The type hint of the property, if it is a property, else None.
  226. """
  227. if not isinstance(attr, (property, hybrid_property)):
  228. return None
  229. hints = get_type_hints(attr.fget)
  230. return hints.get("return", None)
  231. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  232. """Check if an attribute can be accessed on the cls and return its type.
  233. Supports pydantic models, unions, and annotated attributes on rx.Model.
  234. Args:
  235. cls: The class to check.
  236. name: The name of the attribute to check.
  237. Returns:
  238. The type of the attribute, if accessible, or None
  239. """
  240. from reflex.model import Model
  241. try:
  242. attr = getattr(cls, name, None)
  243. except NotImplementedError:
  244. attr = None
  245. if hint := get_property_hint(attr):
  246. return hint
  247. if (
  248. hasattr(cls, "__fields__")
  249. and name in cls.__fields__
  250. and hasattr(cls.__fields__[name], "outer_type_")
  251. ):
  252. # pydantic models
  253. field = cls.__fields__[name]
  254. type_ = field.outer_type_
  255. if isinstance(type_, ModelField):
  256. type_ = type_.type_
  257. if (
  258. not field.required
  259. and field.default is None
  260. and field.default_factory is None
  261. ):
  262. # Ensure frontend uses null coalescing when accessing.
  263. type_ = Optional[type_]
  264. return type_
  265. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  266. insp = sqlalchemy.inspect(cls)
  267. if name in insp.columns:
  268. # check for list types
  269. column = insp.columns[name]
  270. column_type = column.type
  271. try:
  272. type_ = insp.columns[name].type.python_type
  273. except NotImplementedError:
  274. type_ = None
  275. if type_ is not None:
  276. if hasattr(column_type, "item_type"):
  277. try:
  278. item_type = column_type.item_type.python_type # pyright: ignore [reportAttributeAccessIssue]
  279. except NotImplementedError:
  280. item_type = None
  281. if item_type is not None:
  282. if type_ in PrimitiveToAnnotation:
  283. type_ = PrimitiveToAnnotation[type_]
  284. type_ = type_[item_type] # pyright: ignore [reportIndexIssue]
  285. if column.nullable:
  286. type_ = Optional[type_]
  287. return type_
  288. if name in insp.all_orm_descriptors:
  289. descriptor = insp.all_orm_descriptors[name]
  290. if hint := get_property_hint(descriptor):
  291. return hint
  292. if isinstance(descriptor, QueryableAttribute):
  293. prop = descriptor.property
  294. if isinstance(prop, Relationship):
  295. type_ = prop.mapper.class_
  296. # TODO: check for nullable?
  297. type_ = List[type_] if prop.uselist else Optional[type_]
  298. return type_
  299. if isinstance(attr, AssociationProxyInstance):
  300. return List[
  301. get_attribute_access_type(
  302. attr.target_class,
  303. attr.remote_attr.key, # type: ignore[attr-defined]
  304. )
  305. ]
  306. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  307. # Check in the annotations directly (for sqlmodel.Relationship)
  308. hints = get_type_hints(cls)
  309. if name in hints:
  310. type_ = hints[name]
  311. type_origin = get_origin(type_)
  312. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  313. return get_args(type_)[0] # SQLAlchemy v2
  314. if isinstance(type_, ModelField):
  315. return type_.type_ # SQLAlchemy v1.4
  316. return type_
  317. elif is_union(cls):
  318. # Check in each arg of the annotation.
  319. return unionize(
  320. *(get_attribute_access_type(arg, name) for arg in get_args(cls))
  321. )
  322. elif isinstance(cls, type):
  323. # Bare class
  324. if sys.version_info >= (3, 10):
  325. exceptions = NameError
  326. else:
  327. exceptions = (NameError, TypeError)
  328. try:
  329. hints = get_type_hints(cls)
  330. if name in hints:
  331. return hints[name]
  332. except exceptions as e:
  333. console.warn(f"Failed to resolve ForwardRefs for {cls}.{name} due to {e}")
  334. pass
  335. return None # Attribute is not accessible.
  336. @lru_cache()
  337. def get_base_class(cls: GenericType) -> Type | tuple[Type, ...]:
  338. """Get the base class of a class.
  339. Args:
  340. cls: The class.
  341. Returns:
  342. The base class of the class.
  343. Raises:
  344. TypeError: If a literal has multiple types.
  345. """
  346. if is_literal(cls):
  347. # only literals of the same type are supported.
  348. arg_type = type(get_args(cls)[0])
  349. if not all(type(arg) is arg_type for arg in get_args(cls)):
  350. raise TypeError("only literals of the same type are supported")
  351. return type(get_args(cls)[0])
  352. if is_union(cls):
  353. base_classes = []
  354. for arg in get_args(cls):
  355. sub_base_classes = get_base_class(arg)
  356. if isinstance(sub_base_classes, tuple):
  357. base_classes.extend(sub_base_classes)
  358. else:
  359. base_classes.append(sub_base_classes)
  360. return tuple(base_classes)
  361. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  362. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  363. """Check if the breakpoints instance satisfies the typing.
  364. Args:
  365. cls_check: The class to check against.
  366. instance: The instance to check.
  367. Returns:
  368. Whether the breakpoints instance satisfies the typing.
  369. """
  370. cls_check_base = get_base_class(cls_check)
  371. if cls_check_base == Breakpoints:
  372. _, expected_type = get_args(cls_check)
  373. if is_literal(expected_type):
  374. for value in instance.values():
  375. if not isinstance(value, str) or value not in get_args(expected_type):
  376. return False
  377. return True
  378. elif isinstance(cls_check_base, tuple):
  379. # union type, so check all types
  380. return any(
  381. _breakpoints_satisfies_typing(type_to_check, instance)
  382. for type_to_check in get_args(cls_check)
  383. )
  384. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  385. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  386. return False
  387. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  388. """Check if a class is a subclass of another class.
  389. Args:
  390. cls: The class to check.
  391. cls_check: The class to check against.
  392. instance: An instance of cls to aid in checking generics.
  393. Returns:
  394. Whether the class is a subclass of the other class.
  395. Raises:
  396. TypeError: If the base class is not valid for issubclass.
  397. """
  398. # Special check for Any.
  399. if cls_check == Any:
  400. return True
  401. if cls in [Any, Callable, None]:
  402. return False
  403. # Get the base classes.
  404. cls_base = get_base_class(cls)
  405. cls_check_base = get_base_class(cls_check)
  406. # The class we're checking should not be a union.
  407. if isinstance(cls_base, tuple):
  408. return False
  409. # Check that fields of breakpoints match the expected values.
  410. if isinstance(instance, Breakpoints):
  411. return _breakpoints_satisfies_typing(cls_check, instance)
  412. if isinstance(cls_check_base, tuple):
  413. cls_check_base = tuple(
  414. cls_check_one if not is_typeddict(cls_check_one) else dict
  415. for cls_check_one in cls_check_base
  416. )
  417. if is_typeddict(cls_check_base):
  418. cls_check_base = dict
  419. # Check if the types match.
  420. try:
  421. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  422. except TypeError as te:
  423. # These errors typically arise from bad annotations and are hard to
  424. # debug without knowing the type that we tried to compare.
  425. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  426. def does_obj_satisfy_typed_dict(obj: Any, cls: GenericType) -> bool:
  427. """Check if an object satisfies a typed dict.
  428. Args:
  429. obj: The object to check.
  430. cls: The typed dict to check against.
  431. Returns:
  432. Whether the object satisfies the typed dict.
  433. """
  434. if not isinstance(obj, Mapping):
  435. return False
  436. key_names_to_values = get_type_hints(cls)
  437. required_keys: FrozenSet[str] = getattr(cls, "__required_keys__", frozenset())
  438. if not all(
  439. isinstance(key, str)
  440. and key in key_names_to_values
  441. and _isinstance(value, key_names_to_values[key])
  442. for key, value in obj.items()
  443. ):
  444. return False
  445. # TODO in 3.14: Implement https://peps.python.org/pep-0728/ if it's approved
  446. # required keys are all present
  447. return required_keys.issubset(required_keys)
  448. def _isinstance(obj: Any, cls: GenericType, nested: int = 0) -> bool:
  449. """Check if an object is an instance of a class.
  450. Args:
  451. obj: The object to check.
  452. cls: The class to check against.
  453. nested: How many levels deep to check.
  454. Returns:
  455. Whether the object is an instance of the class.
  456. """
  457. if cls is Any:
  458. return True
  459. from reflex.vars import LiteralVar, Var
  460. if cls is Var:
  461. return isinstance(obj, Var)
  462. if isinstance(obj, LiteralVar):
  463. return _isinstance(obj._var_value, cls, nested=nested)
  464. if isinstance(obj, Var):
  465. return _issubclass(obj._var_type, cls)
  466. if cls is None or cls is type(None):
  467. return obj is None
  468. if cls and is_union(cls):
  469. return any(_isinstance(obj, arg, nested=nested) for arg in get_args(cls))
  470. if is_literal(cls):
  471. return obj in get_args(cls)
  472. origin = get_origin(cls)
  473. if origin is None:
  474. # cls is a typed dict
  475. if is_typeddict(cls):
  476. if nested:
  477. return does_obj_satisfy_typed_dict(obj, cls)
  478. return isinstance(obj, dict)
  479. # cls is a float
  480. if cls is float:
  481. return isinstance(obj, (float, int))
  482. # cls is a simple class
  483. return isinstance(obj, cls)
  484. args = get_args(cls)
  485. if not args:
  486. # cls is a simple generic class
  487. return isinstance(obj, origin)
  488. if nested > 0 and args:
  489. if origin is list:
  490. return isinstance(obj, list) and all(
  491. _isinstance(item, args[0], nested=nested - 1) for item in obj
  492. )
  493. if origin is tuple:
  494. if args[-1] is Ellipsis:
  495. return isinstance(obj, tuple) and all(
  496. _isinstance(item, args[0], nested=nested - 1) for item in obj
  497. )
  498. return (
  499. isinstance(obj, tuple)
  500. and len(obj) == len(args)
  501. and all(
  502. _isinstance(item, arg, nested=nested - 1)
  503. for item, arg in zip(obj, args, strict=True)
  504. )
  505. )
  506. if origin in (dict, Mapping, Breakpoints):
  507. return isinstance(obj, Mapping) and all(
  508. _isinstance(key, args[0], nested=nested - 1)
  509. and _isinstance(value, args[1], nested=nested - 1)
  510. for key, value in obj.items()
  511. )
  512. if origin is set:
  513. return isinstance(obj, set) and all(
  514. _isinstance(item, args[0], nested=nested - 1) for item in obj
  515. )
  516. if args:
  517. from reflex.vars import Field
  518. if origin is Field:
  519. return _isinstance(obj, args[0], nested=nested)
  520. return isinstance(obj, get_base_class(cls))
  521. def is_dataframe(value: Type) -> bool:
  522. """Check if the given value is a dataframe.
  523. Args:
  524. value: The value to check.
  525. Returns:
  526. Whether the value is a dataframe.
  527. """
  528. if is_generic_alias(value) or value == Any:
  529. return False
  530. return value.__name__ == "DataFrame"
  531. def is_valid_var_type(type_: Type) -> bool:
  532. """Check if the given type is a valid prop type.
  533. Args:
  534. type_: The type to check.
  535. Returns:
  536. Whether the type is a valid prop type.
  537. """
  538. from reflex.utils import serializers
  539. if is_union(type_):
  540. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  541. return (
  542. _issubclass(type_, StateVar)
  543. or serializers.has_serializer(type_)
  544. or dataclasses.is_dataclass(type_)
  545. )
  546. def is_backend_base_variable(name: str, cls: Type) -> bool:
  547. """Check if this variable name correspond to a backend variable.
  548. Args:
  549. name: The name of the variable to check
  550. cls: The class of the variable to check
  551. Returns:
  552. bool: The result of the check
  553. """
  554. if name in RESERVED_BACKEND_VAR_NAMES:
  555. return False
  556. if not name.startswith("_"):
  557. return False
  558. if name.startswith("__"):
  559. return False
  560. if name.startswith(f"_{cls.__name__}__"):
  561. return False
  562. # Extract the namespace of the original module if defined (dynamic substates).
  563. if callable(getattr(cls, "_get_type_hints", None)):
  564. hints = cls._get_type_hints()
  565. else:
  566. hints = get_type_hints(cls)
  567. if name in hints:
  568. hint = get_origin(hints[name])
  569. if hint == ClassVar:
  570. return False
  571. if name in cls.inherited_backend_vars:
  572. return False
  573. from reflex.vars.base import is_computed_var
  574. if name in cls.__dict__:
  575. value = cls.__dict__[name]
  576. if type(value) is classmethod:
  577. return False
  578. if callable(value):
  579. return False
  580. if isinstance(
  581. value,
  582. (
  583. types.FunctionType,
  584. property,
  585. cached_property,
  586. ),
  587. ) or is_computed_var(value):
  588. return False
  589. return True
  590. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  591. """Check that a value type is found in a list of allowed types.
  592. Args:
  593. value_type: Type of value.
  594. allowed_types: Iterable of allowed types.
  595. Returns:
  596. If the type is found in the allowed types.
  597. """
  598. return get_base_class(value_type) in allowed_types
  599. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  600. """Check that a prop value is in a list of allowed types.
  601. Does the check in a way that works regardless if it's a raw value or a state Var.
  602. Args:
  603. prop: The prop to check.
  604. allowed_types: The list of allowed types.
  605. Returns:
  606. If the prop type match one of the allowed_types.
  607. """
  608. from reflex.vars import Var
  609. type_ = prop._var_type if isinstance(prop, Var) else type(prop)
  610. return type_ in allowed_types
  611. def is_encoded_fstring(value: Any) -> bool:
  612. """Check if a value is an encoded Var f-string.
  613. Args:
  614. value: The value string to check.
  615. Returns:
  616. Whether the value is an f-string
  617. """
  618. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  619. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  620. """Check that a value is a valid literal.
  621. Args:
  622. key: The prop name.
  623. value: The prop value to validate.
  624. expected_type: The expected type(literal type).
  625. comp_name: Name of the component.
  626. Raises:
  627. ValueError: When the value is not a valid literal.
  628. """
  629. from reflex.vars import Var
  630. if (
  631. is_literal(expected_type)
  632. and not isinstance(value, Var) # validating vars is not supported yet.
  633. and not is_encoded_fstring(value) # f-strings are not supported.
  634. and value not in expected_type.__args__
  635. ):
  636. allowed_values = expected_type.__args__
  637. if value not in allowed_values:
  638. allowed_value_str = ",".join(
  639. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  640. )
  641. value_str = f"'{value}'" if isinstance(value, str) else value
  642. raise ValueError(
  643. f"prop value for {key!s} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  644. )
  645. def validate_parameter_literals(func: Callable):
  646. """Decorator to check that the arguments passed to a function
  647. correspond to the correct function parameter if it (the parameter)
  648. is a literal type.
  649. Args:
  650. func: The function to validate.
  651. Returns:
  652. The wrapper function.
  653. """
  654. @wraps(func)
  655. def wrapper(*args, **kwargs):
  656. func_params = list(inspect.signature(func).parameters.items())
  657. annotations = {param[0]: param[1].annotation for param in func_params}
  658. # validate args
  659. for param, arg in zip(annotations, args, strict=False):
  660. if annotations[param] is inspect.Parameter.empty:
  661. continue
  662. validate_literal(param, arg, annotations[param], func.__name__)
  663. # validate kwargs.
  664. for key, value in kwargs.items():
  665. annotation = annotations.get(key)
  666. if not annotation or annotation is inspect.Parameter.empty:
  667. continue
  668. validate_literal(key, value, annotation, func.__name__)
  669. return func(*args, **kwargs)
  670. return wrapper
  671. # Store this here for performance.
  672. StateBases = get_base_class(StateVar)
  673. StateIterBases = get_base_class(StateIterVar)
  674. def safe_issubclass(cls: Any, class_or_tuple: Any, /) -> bool:
  675. """Check if a class is a subclass of another class or a tuple of classes.
  676. Args:
  677. cls: The class to check.
  678. class_or_tuple: The class or tuple of classes to check against.
  679. Returns:
  680. Whether the class is a subclass of the other class or tuple of classes.
  681. """
  682. if cls is class_or_tuple or (
  683. isinstance(class_or_tuple, tuple) and cls in class_or_tuple
  684. ):
  685. return True
  686. try:
  687. return issubclass(cls, class_or_tuple)
  688. except TypeError:
  689. return False
  690. def typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> bool:
  691. """Check if a type hint is a subclass of another type hint.
  692. Args:
  693. possible_subclass: The type hint to check.
  694. possible_superclass: The type hint to check against.
  695. Returns:
  696. Whether the type hint is a subclass of the other type hint.
  697. """
  698. if isinstance(possible_subclass, Sequence) and isinstance(
  699. possible_superclass, Sequence
  700. ):
  701. return all(
  702. typehint_issubclass(subclass, superclass)
  703. for subclass, superclass in zip(
  704. possible_subclass, possible_superclass, strict=False
  705. )
  706. )
  707. if possible_subclass is possible_superclass:
  708. return True
  709. if possible_superclass is Any:
  710. return True
  711. if possible_subclass is Any:
  712. return False
  713. if isinstance(
  714. possible_subclass, (TypeVar, typing_extensions.TypeVar)
  715. ) or isinstance(possible_superclass, (TypeVar, typing_extensions.TypeVar)):
  716. return True
  717. provided_type_origin = get_origin(possible_subclass)
  718. accepted_type_origin = get_origin(possible_superclass)
  719. if provided_type_origin is None and accepted_type_origin is None:
  720. # In this case, we are dealing with a non-generic type, so we can use issubclass
  721. return safe_issubclass(possible_subclass, possible_superclass)
  722. # Remove this check when Python 3.10 is the minimum supported version
  723. if hasattr(types, "UnionType"):
  724. provided_type_origin = (
  725. Union if provided_type_origin is types.UnionType else provided_type_origin
  726. )
  727. accepted_type_origin = (
  728. Union if accepted_type_origin is types.UnionType else accepted_type_origin
  729. )
  730. # Get type arguments (e.g., [float, int] for Dict[float, int])
  731. provided_args = get_args(possible_subclass)
  732. accepted_args = get_args(possible_superclass)
  733. if provided_type_origin is Union:
  734. return all(
  735. typehint_issubclass(provided_arg, possible_superclass)
  736. for provided_arg in provided_args
  737. )
  738. if accepted_type_origin is Union:
  739. return any(
  740. typehint_issubclass(possible_subclass, accepted_arg)
  741. for accepted_arg in accepted_args
  742. )
  743. # Check specifically for Sequence and Iterable
  744. if (accepted_type_origin or possible_superclass) in (
  745. Sequence,
  746. abc.Sequence,
  747. Iterable,
  748. abc.Iterable,
  749. ):
  750. iterable_type = accepted_args[0] if accepted_args else Any
  751. if provided_type_origin is None:
  752. if not safe_issubclass(
  753. possible_subclass, (accepted_type_origin or possible_superclass)
  754. ):
  755. return False
  756. if safe_issubclass(possible_subclass, str) and not isinstance(
  757. iterable_type, TypeVar
  758. ):
  759. return typehint_issubclass(str, iterable_type)
  760. return True
  761. if not safe_issubclass(
  762. provided_type_origin, (accepted_type_origin or possible_superclass)
  763. ):
  764. return False
  765. if not isinstance(iterable_type, (TypeVar, typing_extensions.TypeVar)):
  766. if provided_type_origin in (list, tuple, set):
  767. # Ensure all specific types are compatible with accepted types
  768. return all(
  769. typehint_issubclass(provided_arg, iterable_type)
  770. for provided_arg in provided_args
  771. if provided_arg is not ... # Ellipsis in Tuples
  772. )
  773. if possible_subclass is dict:
  774. # Ensure all specific types are compatible with accepted types
  775. return all(
  776. typehint_issubclass(provided_arg, iterable_type)
  777. for provided_arg in provided_args[:1]
  778. )
  779. return True
  780. # Check if the origin of both types is the same (e.g., list for List[int])
  781. if not safe_issubclass(
  782. provided_type_origin or possible_subclass,
  783. accepted_type_origin or possible_superclass,
  784. ):
  785. return False
  786. # Ensure all specific types are compatible with accepted types
  787. # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
  788. # It also ignores when the length of the arguments is different
  789. return all(
  790. typehint_issubclass(provided_arg, accepted_arg)
  791. for provided_arg, accepted_arg in zip(
  792. provided_args, accepted_args, strict=False
  793. )
  794. if accepted_arg is not Any and not isinstance(accepted_arg, TypeVar)
  795. )
  796. def safe_typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> bool:
  797. """Check if a type hint is a subclass of another type hint.
  798. Args:
  799. possible_subclass: The type hint to check.
  800. possible_superclass: The type hint to check against.
  801. Returns:
  802. Whether the type hint is a subclass of the other type hint.
  803. """
  804. try:
  805. return typehint_issubclass(possible_subclass, possible_superclass)
  806. except Exception:
  807. return False