types.py 28 KB

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