types.py 26 KB

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