types.py 26 KB

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