types.py 33 KB

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