types.py 26 KB

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