types.py 27 KB

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