types.py 26 KB

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