types.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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: list[type] = [_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) -> GenericType:
  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 | tuple[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. base_classes = []
  349. for arg in get_args(cls):
  350. sub_base_classes = get_base_class(arg)
  351. if isinstance(sub_base_classes, tuple):
  352. base_classes.extend(sub_base_classes)
  353. else:
  354. base_classes.append(sub_base_classes)
  355. return tuple(base_classes)
  356. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  357. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  358. """Check if the breakpoints instance satisfies the typing.
  359. Args:
  360. cls_check: The class to check against.
  361. instance: The instance to check.
  362. Returns:
  363. Whether the breakpoints instance satisfies the typing.
  364. """
  365. cls_check_base = get_base_class(cls_check)
  366. if cls_check_base == Breakpoints:
  367. _, expected_type = get_args(cls_check)
  368. if is_literal(expected_type):
  369. for value in instance.values():
  370. if not isinstance(value, str) or value not in get_args(expected_type):
  371. return False
  372. return True
  373. elif isinstance(cls_check_base, tuple):
  374. # union type, so check all types
  375. return any(
  376. _breakpoints_satisfies_typing(type_to_check, instance)
  377. for type_to_check in get_args(cls_check)
  378. )
  379. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  380. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  381. return False
  382. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  383. """Check if a class is a subclass of another class.
  384. Args:
  385. cls: The class to check.
  386. cls_check: The class to check against.
  387. instance: An instance of cls to aid in checking generics.
  388. Returns:
  389. Whether the class is a subclass of the other class.
  390. Raises:
  391. TypeError: If the base class is not valid for issubclass.
  392. """
  393. # Special check for Any.
  394. if cls_check == Any:
  395. return True
  396. if cls in [Any, Callable, None]:
  397. return False
  398. # Get the base classes.
  399. cls_base = get_base_class(cls)
  400. cls_check_base = get_base_class(cls_check)
  401. # The class we're checking should not be a union.
  402. if isinstance(cls_base, tuple):
  403. return False
  404. # Check that fields of breakpoints match the expected values.
  405. if isinstance(instance, Breakpoints):
  406. return _breakpoints_satisfies_typing(cls_check, instance)
  407. if isinstance(cls_check_base, tuple):
  408. cls_check_base = tuple(
  409. cls_check_one if not is_typeddict(cls_check_one) else dict
  410. for cls_check_one in cls_check_base
  411. )
  412. if is_typeddict(cls_check_base):
  413. cls_check_base = dict
  414. # Check if the types match.
  415. try:
  416. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  417. except TypeError as te:
  418. # These errors typically arise from bad annotations and are hard to
  419. # debug without knowing the type that we tried to compare.
  420. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  421. def does_obj_satisfy_typed_dict(obj: Any, cls: GenericType) -> bool:
  422. """Check if an object satisfies a typed dict.
  423. Args:
  424. obj: The object to check.
  425. cls: The typed dict to check against.
  426. Returns:
  427. Whether the object satisfies the typed dict.
  428. """
  429. if not isinstance(obj, Mapping):
  430. return False
  431. key_names_to_values = get_type_hints(cls)
  432. required_keys: FrozenSet[str] = getattr(cls, "__required_keys__", frozenset())
  433. if not all(
  434. isinstance(key, str)
  435. and key in key_names_to_values
  436. and _isinstance(value, key_names_to_values[key])
  437. for key, value in obj.items()
  438. ):
  439. return False
  440. # TODO in 3.14: Implement https://peps.python.org/pep-0728/ if it's approved
  441. # required keys are all present
  442. return required_keys.issubset(required_keys)
  443. def _isinstance(obj: Any, cls: GenericType, nested: bool = False) -> bool:
  444. """Check if an object is an instance of a class.
  445. Args:
  446. obj: The object to check.
  447. cls: The class to check against.
  448. nested: Whether the check is nested.
  449. Returns:
  450. Whether the object is an instance of the class.
  451. """
  452. if cls is Any:
  453. return True
  454. if cls is None or cls is type(None):
  455. return obj is None
  456. if is_literal(cls):
  457. return obj in get_args(cls)
  458. if is_union(cls):
  459. return any(_isinstance(obj, arg) for arg in get_args(cls))
  460. origin = get_origin(cls)
  461. if origin is None:
  462. # cls is a typed dict
  463. if is_typeddict(cls):
  464. if nested:
  465. return does_obj_satisfy_typed_dict(obj, cls)
  466. return isinstance(obj, dict)
  467. # cls is a float
  468. if cls is float:
  469. return isinstance(obj, (float, int))
  470. # cls is a simple class
  471. return isinstance(obj, cls)
  472. args = get_args(cls)
  473. if not args:
  474. # cls is a simple generic class
  475. return isinstance(obj, origin)
  476. if nested and args:
  477. if origin is list:
  478. return isinstance(obj, list) and all(
  479. _isinstance(item, args[0]) for item in obj
  480. )
  481. if origin is tuple:
  482. if args[-1] is Ellipsis:
  483. return isinstance(obj, tuple) and all(
  484. _isinstance(item, args[0]) for item in obj
  485. )
  486. return (
  487. isinstance(obj, tuple)
  488. and len(obj) == len(args)
  489. and all(_isinstance(item, arg) for item, arg in zip(obj, args))
  490. )
  491. if origin in (dict, Breakpoints):
  492. return isinstance(obj, dict) and all(
  493. _isinstance(key, args[0]) and _isinstance(value, args[1])
  494. for key, value in obj.items()
  495. )
  496. if origin is set:
  497. return isinstance(obj, set) and all(
  498. _isinstance(item, args[0]) for item in obj
  499. )
  500. if args:
  501. from reflex.vars import Field
  502. if origin is Field:
  503. return _isinstance(obj, args[0])
  504. return isinstance(obj, get_base_class(cls))
  505. def is_dataframe(value: Type) -> bool:
  506. """Check if the given value is a dataframe.
  507. Args:
  508. value: The value to check.
  509. Returns:
  510. Whether the value is a dataframe.
  511. """
  512. if is_generic_alias(value) or value == Any:
  513. return False
  514. return value.__name__ == "DataFrame"
  515. def is_valid_var_type(type_: Type) -> bool:
  516. """Check if the given type is a valid prop type.
  517. Args:
  518. type_: The type to check.
  519. Returns:
  520. Whether the type is a valid prop type.
  521. """
  522. from reflex.utils import serializers
  523. if is_union(type_):
  524. return all((is_valid_var_type(arg) for arg in get_args(type_)))
  525. return (
  526. _issubclass(type_, StateVar)
  527. or serializers.has_serializer(type_)
  528. or dataclasses.is_dataclass(type_)
  529. )
  530. def is_backend_base_variable(name: str, cls: Type) -> bool:
  531. """Check if this variable name correspond to a backend variable.
  532. Args:
  533. name: The name of the variable to check
  534. cls: The class of the variable to check
  535. Returns:
  536. bool: The result of the check
  537. """
  538. if name in RESERVED_BACKEND_VAR_NAMES:
  539. return False
  540. if not name.startswith("_"):
  541. return False
  542. if name.startswith("__"):
  543. return False
  544. if name.startswith(f"_{cls.__name__}__"):
  545. return False
  546. # Extract the namespace of the original module if defined (dynamic substates).
  547. if callable(getattr(cls, "_get_type_hints", None)):
  548. hints = cls._get_type_hints()
  549. else:
  550. hints = get_type_hints(cls)
  551. if name in hints:
  552. hint = get_origin(hints[name])
  553. if hint == ClassVar:
  554. return False
  555. if name in cls.inherited_backend_vars:
  556. return False
  557. from reflex.vars.base import is_computed_var
  558. if name in cls.__dict__:
  559. value = cls.__dict__[name]
  560. if type(value) is classmethod:
  561. return False
  562. if callable(value):
  563. return False
  564. if isinstance(
  565. value,
  566. (
  567. types.FunctionType,
  568. property,
  569. cached_property,
  570. ),
  571. ) or is_computed_var(value):
  572. return False
  573. return True
  574. def check_type_in_allowed_types(value_type: Type, allowed_types: Iterable) -> bool:
  575. """Check that a value type is found in a list of allowed types.
  576. Args:
  577. value_type: Type of value.
  578. allowed_types: Iterable of allowed types.
  579. Returns:
  580. If the type is found in the allowed types.
  581. """
  582. return get_base_class(value_type) in allowed_types
  583. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  584. """Check that a prop value is in a list of allowed types.
  585. Does the check in a way that works regardless if it's a raw value or a state Var.
  586. Args:
  587. prop: The prop to check.
  588. allowed_types: The list of allowed types.
  589. Returns:
  590. If the prop type match one of the allowed_types.
  591. """
  592. from reflex.vars import Var
  593. type_ = prop._var_type if _isinstance(prop, Var) else type(prop)
  594. return type_ in allowed_types
  595. def is_encoded_fstring(value) -> bool:
  596. """Check if a value is an encoded Var f-string.
  597. Args:
  598. value: The value string to check.
  599. Returns:
  600. Whether the value is an f-string
  601. """
  602. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  603. def validate_literal(key: str, value: Any, expected_type: Type, comp_name: str):
  604. """Check that a value is a valid literal.
  605. Args:
  606. key: The prop name.
  607. value: The prop value to validate.
  608. expected_type: The expected type(literal type).
  609. comp_name: Name of the component.
  610. Raises:
  611. ValueError: When the value is not a valid literal.
  612. """
  613. from reflex.vars import Var
  614. if (
  615. is_literal(expected_type)
  616. and not isinstance(value, Var) # validating vars is not supported yet.
  617. and not is_encoded_fstring(value) # f-strings are not supported.
  618. and value not in expected_type.__args__
  619. ):
  620. allowed_values = expected_type.__args__
  621. if value not in allowed_values:
  622. allowed_value_str = ",".join(
  623. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  624. )
  625. value_str = f"'{value}'" if isinstance(value, str) else value
  626. raise ValueError(
  627. f"prop value for {key!s} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  628. )
  629. def validate_parameter_literals(func):
  630. """Decorator to check that the arguments passed to a function
  631. correspond to the correct function parameter if it (the parameter)
  632. is a literal type.
  633. Args:
  634. func: The function to validate.
  635. Returns:
  636. The wrapper function.
  637. """
  638. @wraps(func)
  639. def wrapper(*args, **kwargs):
  640. func_params = list(inspect.signature(func).parameters.items())
  641. annotations = {param[0]: param[1].annotation for param in func_params}
  642. # validate args
  643. for param, arg in zip(annotations, args):
  644. if annotations[param] is inspect.Parameter.empty:
  645. continue
  646. validate_literal(param, arg, annotations[param], func.__name__)
  647. # validate kwargs.
  648. for key, value in kwargs.items():
  649. annotation = annotations.get(key)
  650. if not annotation or annotation is inspect.Parameter.empty:
  651. continue
  652. validate_literal(key, value, annotation, func.__name__)
  653. return func(*args, **kwargs)
  654. return wrapper
  655. # Store this here for performance.
  656. StateBases = get_base_class(StateVar)
  657. StateIterBases = get_base_class(StateIterVar)
  658. def safe_issubclass(cls: Any, class_or_tuple: Any, /) -> bool:
  659. """Check if a class is a subclass of another class or a tuple of classes.
  660. Args:
  661. cls: The class to check.
  662. class_or_tuple: The class or tuple of classes to check against.
  663. Returns:
  664. Whether the class is a subclass of the other class or tuple of classes.
  665. Raises:
  666. TypeError: If the arguments are invalid.
  667. """
  668. try:
  669. return issubclass(cls, class_or_tuple)
  670. except TypeError as e:
  671. raise TypeError(
  672. f"Invalid arguments for issubclass: {cls}, {class_or_tuple}"
  673. ) from e
  674. def infallible_issubclass(cls: Any, class_or_tuple: Any, /) -> bool:
  675. """Check if a class is a subclass of another class or a tuple of classes.
  676. Args:
  677. cls: The class to check.
  678. class_or_tuple: The class or tuple of classes to check against.
  679. Returns:
  680. Whether the class is a subclass of the other class or tuple of classes.
  681. """
  682. if cls is class_or_tuple or (
  683. isinstance(class_or_tuple, tuple) and cls in class_or_tuple
  684. ):
  685. return True
  686. try:
  687. return issubclass(cls, class_or_tuple)
  688. except TypeError:
  689. return False
  690. def typehint_issubclass(possible_subclass: Any, possible_superclass: Any) -> bool:
  691. """Check if a type hint is a subclass of another type hint.
  692. Args:
  693. possible_subclass: The type hint to check.
  694. possible_superclass: The type hint to check against.
  695. Returns:
  696. Whether the type hint is a subclass of the other type hint.
  697. """
  698. if isinstance(possible_subclass, Sequence) and isinstance(
  699. possible_superclass, Sequence
  700. ):
  701. return all(
  702. typehint_issubclass(subclass, superclass)
  703. for subclass, superclass in zip(possible_subclass, possible_superclass)
  704. )
  705. if possible_subclass is possible_superclass:
  706. return True
  707. if possible_superclass is Any:
  708. return True
  709. if possible_subclass is Any:
  710. return False
  711. if isinstance(
  712. possible_subclass, (TypeVar, typing_extensions.TypeVar)
  713. ) or isinstance(possible_superclass, (TypeVar, typing_extensions.TypeVar)):
  714. return True
  715. provided_type_origin = get_origin(possible_subclass)
  716. accepted_type_origin = get_origin(possible_superclass)
  717. if provided_type_origin is None and accepted_type_origin is None:
  718. # In this case, we are dealing with a non-generic type, so we can use issubclass
  719. return safe_issubclass(possible_subclass, possible_superclass)
  720. # Remove this check when Python 3.10 is the minimum supported version
  721. if hasattr(types, "UnionType"):
  722. provided_type_origin = (
  723. Union if provided_type_origin is types.UnionType else provided_type_origin
  724. )
  725. accepted_type_origin = (
  726. Union if accepted_type_origin is types.UnionType else accepted_type_origin
  727. )
  728. # Get type arguments (e.g., [float, int] for Dict[float, int])
  729. provided_args = get_args(possible_subclass)
  730. accepted_args = get_args(possible_superclass)
  731. if provided_type_origin is Union:
  732. return all(
  733. typehint_issubclass(provided_arg, possible_superclass)
  734. for provided_arg in provided_args
  735. )
  736. if accepted_type_origin is Union:
  737. return any(
  738. typehint_issubclass(possible_subclass, accepted_arg)
  739. for accepted_arg in accepted_args
  740. )
  741. # Check specifically for Sequence and Iterable
  742. if (accepted_type_origin or possible_superclass) in (
  743. Sequence,
  744. abc.Sequence,
  745. Iterable,
  746. abc.Iterable,
  747. ):
  748. iterable_type = accepted_args[0] if accepted_args else Any
  749. if provided_type_origin is None:
  750. if not safe_issubclass(
  751. possible_subclass, (accepted_type_origin or possible_superclass)
  752. ):
  753. return False
  754. if safe_issubclass(possible_subclass, str) and not isinstance(
  755. iterable_type, TypeVar
  756. ):
  757. return typehint_issubclass(str, iterable_type)
  758. return True
  759. if not safe_issubclass(
  760. provided_type_origin, (accepted_type_origin or possible_superclass)
  761. ):
  762. return False
  763. if not isinstance(iterable_type, (TypeVar, typing_extensions.TypeVar)):
  764. if provided_type_origin in (list, tuple, set):
  765. # Ensure all specific types are compatible with accepted types
  766. return all(
  767. typehint_issubclass(provided_arg, iterable_type)
  768. for provided_arg in provided_args
  769. if provided_arg is not ... # Ellipsis in Tuples
  770. )
  771. if possible_subclass is dict:
  772. # Ensure all specific types are compatible with accepted types
  773. return all(
  774. typehint_issubclass(provided_arg, iterable_type)
  775. for provided_arg in provided_args[:1]
  776. )
  777. return True
  778. # Check if the origin of both types is the same (e.g., list for List[int])
  779. if not infallible_issubclass(
  780. provided_type_origin or possible_subclass,
  781. accepted_type_origin or possible_superclass,
  782. ):
  783. return False
  784. # Ensure all specific types are compatible with accepted types
  785. # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
  786. # It also ignores when the length of the arguments is different
  787. return all(
  788. typehint_issubclass(provided_arg, accepted_arg)
  789. for provided_arg, accepted_arg in zip(provided_args, accepted_args)
  790. if accepted_arg is not Any and not isinstance(accepted_arg, TypeVar)
  791. )