types.py 33 KB

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