types.py 27 KB

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