types.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  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. Awaitable,
  13. ClassVar,
  14. Dict,
  15. ForwardRef,
  16. List,
  17. Literal,
  18. MutableMapping,
  19. NoReturn,
  20. Tuple,
  21. Union,
  22. _GenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  23. _SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  24. get_args,
  25. )
  26. from typing import get_origin as get_origin_og
  27. from typing import get_type_hints as get_type_hints_og
  28. import sqlalchemy
  29. from pydantic.v1.fields import ModelField
  30. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  31. from sqlalchemy.ext.hybrid import hybrid_property
  32. from sqlalchemy.orm import DeclarativeBase, Mapped, QueryableAttribute, Relationship
  33. from typing_extensions import Self as Self
  34. from typing_extensions import is_typeddict
  35. from typing_extensions import override as override
  36. import reflex
  37. from reflex import constants
  38. from reflex.base import Base
  39. from reflex.components.core.breakpoints import Breakpoints
  40. from reflex.utils import console
  41. # Potential GenericAlias types for isinstance checks.
  42. GenericAliasTypes = (_GenericAlias, GenericAlias, _SpecialGenericAlias)
  43. # Potential Union types for isinstance checks.
  44. UnionTypes = (Union, types.UnionType)
  45. # Union of generic types.
  46. GenericType = type | _GenericAlias
  47. # Valid state var types.
  48. JSONType = {str, int, float, bool}
  49. PrimitiveType = int | float | bool | str | list | dict | set | tuple
  50. PrimitiveTypes = (int, float, bool, str, list, dict, set, tuple)
  51. StateVar = PrimitiveType | Base | None
  52. StateIterVar = list | set | tuple
  53. if TYPE_CHECKING:
  54. from reflex.vars.base import Var
  55. ArgsSpec = (
  56. Callable[[], Sequence[Var]]
  57. | Callable[[Var], Sequence[Var]]
  58. | Callable[[Var, Var], Sequence[Var]]
  59. | Callable[[Var, Var, Var], Sequence[Var]]
  60. | Callable[[Var, Var, Var, Var], Sequence[Var]]
  61. | Callable[[Var, Var, Var, Var, Var], Sequence[Var]]
  62. | Callable[[Var, Var, Var, Var, Var, Var], Sequence[Var]]
  63. | Callable[[Var, Var, Var, Var, Var, Var, Var], Sequence[Var]]
  64. )
  65. else:
  66. ArgsSpec = Callable[..., list[Any]]
  67. Scope = MutableMapping[str, Any]
  68. Message = MutableMapping[str, Any]
  69. Receive = Callable[[], Awaitable[Message]]
  70. Send = Callable[[Message], Awaitable[None]]
  71. ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
  72. PrimitiveToAnnotation = {
  73. list: List, # noqa: UP006
  74. tuple: Tuple, # noqa: UP006
  75. dict: Dict, # noqa: UP006
  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_cached(tp: Any):
  100. return get_origin_og(tp)
  101. def get_origin(tp: Any):
  102. """Get the origin of a class.
  103. Args:
  104. tp: The class to get the origin of.
  105. Returns:
  106. The origin of the class.
  107. """
  108. return (
  109. origin
  110. if (origin := getattr(tp, "__origin__", None)) is not None
  111. else _get_origin_cached(tp)
  112. )
  113. @lru_cache
  114. def is_generic_alias(cls: GenericType) -> bool:
  115. """Check whether the class is a generic alias.
  116. Args:
  117. cls: The class to check.
  118. Returns:
  119. Whether the class is a generic alias.
  120. """
  121. return isinstance(cls, GenericAliasTypes)
  122. @lru_cache
  123. def get_type_hints(obj: Any) -> dict[str, Any]:
  124. """Get the type hints of a class.
  125. Args:
  126. obj: The class to get the type hints of.
  127. Returns:
  128. The type hints of the class.
  129. """
  130. return get_type_hints_og(obj)
  131. def _unionize(args: list[GenericType]) -> GenericType:
  132. if not args:
  133. return Any # pyright: ignore [reportReturnType]
  134. if len(args) == 1:
  135. return args[0]
  136. return Union[tuple(args)] # noqa: UP007
  137. def unionize(*args: GenericType) -> type:
  138. """Unionize the types.
  139. Args:
  140. args: The types to unionize.
  141. Returns:
  142. The unionized types.
  143. """
  144. return _unionize([arg for arg in args if arg is not NoReturn])
  145. def is_none(cls: GenericType) -> bool:
  146. """Check if a class is None.
  147. Args:
  148. cls: The class to check.
  149. Returns:
  150. Whether the class is None.
  151. """
  152. return cls is type(None) or cls is None
  153. def is_union(cls: GenericType) -> bool:
  154. """Check if a class is a Union.
  155. Args:
  156. cls: The class to check.
  157. Returns:
  158. Whether the class is a Union.
  159. """
  160. origin = getattr(cls, "__origin__", None)
  161. if origin is Union:
  162. return True
  163. return origin is None and isinstance(cls, types.UnionType)
  164. def is_literal(cls: GenericType) -> bool:
  165. """Check if a class is a Literal.
  166. Args:
  167. cls: The class to check.
  168. Returns:
  169. Whether the class is a literal.
  170. """
  171. return getattr(cls, "__origin__", None) is Literal
  172. def has_args(cls: type) -> bool:
  173. """Check if the class has generic parameters.
  174. Args:
  175. cls: The class to check.
  176. Returns:
  177. Whether the class has generic
  178. """
  179. if get_args(cls):
  180. return True
  181. # Check if the class inherits from a generic class (using __orig_bases__)
  182. if hasattr(cls, "__orig_bases__"):
  183. for base in cls.__orig_bases__:
  184. if get_args(base):
  185. return True
  186. return False
  187. def is_optional(cls: GenericType) -> bool:
  188. """Check if a class is an Optional.
  189. Args:
  190. cls: The class to check.
  191. Returns:
  192. Whether the class is an Optional.
  193. """
  194. return is_union(cls) and type(None) in get_args(cls)
  195. def true_type_for_pydantic_field(f: ModelField):
  196. """Get the type for a pydantic field.
  197. Args:
  198. f: The field to get the type for.
  199. Returns:
  200. The type for the field.
  201. """
  202. if not isinstance(f.annotation, (str, ForwardRef)):
  203. return f.annotation
  204. type_ = f.outer_type_
  205. if (
  206. f.field_info.default is None
  207. or (isinstance(f.annotation, str) and f.annotation.startswith("Optional"))
  208. or (
  209. isinstance(f.annotation, ForwardRef)
  210. and f.annotation.__forward_arg__.startswith("Optional")
  211. )
  212. ) and not is_optional(type_):
  213. return type_ | None
  214. return type_
  215. def value_inside_optional(cls: GenericType) -> GenericType:
  216. """Get the value inside an Optional type or the original type.
  217. Args:
  218. cls: The class to check.
  219. Returns:
  220. The value inside the Optional type or the original type.
  221. """
  222. if is_union(cls) and len(args := get_args(cls)) >= 2 and type(None) in args:
  223. if len(args) == 2:
  224. return args[0] if args[1] is type(None) else args[1]
  225. return unionize(*[arg for arg in args if arg is not type(None)])
  226. return cls
  227. def get_field_type(cls: GenericType, field_name: str) -> GenericType | None:
  228. """Get the type of a field in a class.
  229. Args:
  230. cls: The class to check.
  231. field_name: The name of the field to check.
  232. Returns:
  233. The type of the field, if it exists, else None.
  234. """
  235. if (
  236. hasattr(cls, "__fields__")
  237. and field_name in cls.__fields__
  238. and hasattr(cls.__fields__[field_name], "annotation")
  239. and not isinstance(cls.__fields__[field_name].annotation, (str, ForwardRef))
  240. ):
  241. return cls.__fields__[field_name].annotation
  242. type_hints = get_type_hints(cls)
  243. return type_hints.get(field_name, None)
  244. def get_property_hint(attr: Any | None) -> GenericType | None:
  245. """Check if an attribute is a property and return its type hint.
  246. Args:
  247. attr: The descriptor to check.
  248. Returns:
  249. The type hint of the property, if it is a property, else None.
  250. """
  251. if not isinstance(attr, (property, hybrid_property)):
  252. return None
  253. hints = get_type_hints(attr.fget)
  254. return hints.get("return", None)
  255. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  256. """Check if an attribute can be accessed on the cls and return its type.
  257. Supports pydantic models, unions, and annotated attributes on rx.Model.
  258. Args:
  259. cls: The class to check.
  260. name: The name of the attribute to check.
  261. Returns:
  262. The type of the attribute, if accessible, or None
  263. """
  264. from reflex.model import Model
  265. try:
  266. attr = getattr(cls, name, None)
  267. except NotImplementedError:
  268. attr = None
  269. if hint := get_property_hint(attr):
  270. return hint
  271. if hasattr(cls, "__fields__") and name in cls.__fields__:
  272. # pydantic models
  273. return get_field_type(cls, name)
  274. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  275. insp = sqlalchemy.inspect(cls)
  276. if name in insp.columns:
  277. # check for list types
  278. column = insp.columns[name]
  279. column_type = column.type
  280. try:
  281. type_ = insp.columns[name].type.python_type
  282. except NotImplementedError:
  283. type_ = None
  284. if type_ is not None:
  285. if hasattr(column_type, "item_type"):
  286. try:
  287. item_type = column_type.item_type.python_type # pyright: ignore [reportAttributeAccessIssue]
  288. except NotImplementedError:
  289. item_type = None
  290. if item_type is not None:
  291. if type_ in PrimitiveToAnnotation:
  292. type_ = PrimitiveToAnnotation[type_]
  293. type_ = type_[item_type] # pyright: ignore [reportIndexIssue]
  294. if column.nullable:
  295. type_ = type_ | None
  296. return type_
  297. if name in insp.all_orm_descriptors:
  298. descriptor = insp.all_orm_descriptors[name]
  299. if hint := get_property_hint(descriptor):
  300. return hint
  301. if isinstance(descriptor, QueryableAttribute):
  302. prop = descriptor.property
  303. if isinstance(prop, Relationship):
  304. type_ = prop.mapper.class_
  305. # TODO: check for nullable?
  306. type_ = list[type_] if prop.uselist else type_ | None
  307. return type_
  308. if isinstance(attr, AssociationProxyInstance):
  309. return list[
  310. get_attribute_access_type(
  311. attr.target_class,
  312. attr.remote_attr.key, # type: ignore[attr-defined]
  313. )
  314. ]
  315. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  316. # Check in the annotations directly (for sqlmodel.Relationship)
  317. hints = get_type_hints(cls)
  318. if name in hints:
  319. type_ = hints[name]
  320. type_origin = get_origin(type_)
  321. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  322. return get_args(type_)[0] # SQLAlchemy v2
  323. if isinstance(type_, ModelField):
  324. return type_.type_ # SQLAlchemy v1.4
  325. return type_
  326. elif is_union(cls):
  327. # Check in each arg of the annotation.
  328. return unionize(
  329. *(get_attribute_access_type(arg, name) for arg in get_args(cls))
  330. )
  331. elif isinstance(cls, type):
  332. # Bare class
  333. exceptions = NameError
  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 is not None 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 origin is Var and args:
  513. # cls is a Var
  514. return _isinstance(
  515. obj,
  516. args[0],
  517. nested=nested,
  518. treat_var_as_type=treat_var_as_type,
  519. treat_mutable_obj_as_immutable=treat_mutable_obj_as_immutable,
  520. )
  521. if nested > 0 and args:
  522. if origin is list:
  523. expected_class = Sequence if treat_mutable_obj_as_immutable else list
  524. return isinstance(obj, expected_class) and all(
  525. _isinstance(
  526. item,
  527. args[0],
  528. nested=nested - 1,
  529. treat_var_as_type=treat_var_as_type,
  530. )
  531. for item in obj
  532. )
  533. if origin is tuple:
  534. if args[-1] is Ellipsis:
  535. return isinstance(obj, tuple) and all(
  536. _isinstance(
  537. item,
  538. args[0],
  539. nested=nested - 1,
  540. treat_var_as_type=treat_var_as_type,
  541. )
  542. for item in obj
  543. )
  544. return (
  545. isinstance(obj, tuple)
  546. and len(obj) == len(args)
  547. and all(
  548. _isinstance(
  549. item,
  550. arg,
  551. nested=nested - 1,
  552. treat_var_as_type=treat_var_as_type,
  553. )
  554. for item, arg in zip(obj, args, strict=True)
  555. )
  556. )
  557. if origin in (dict, Mapping, Breakpoints):
  558. expected_class = (
  559. dict
  560. if origin is dict and not treat_mutable_obj_as_immutable
  561. else Mapping
  562. )
  563. return isinstance(obj, expected_class) and all(
  564. _isinstance(
  565. key, args[0], nested=nested - 1, treat_var_as_type=treat_var_as_type
  566. )
  567. and _isinstance(
  568. value,
  569. args[1],
  570. nested=nested - 1,
  571. treat_var_as_type=treat_var_as_type,
  572. )
  573. for key, value in obj.items()
  574. )
  575. if origin is set:
  576. expected_class = Sequence if treat_mutable_obj_as_immutable else set
  577. return isinstance(obj, expected_class) and all(
  578. _isinstance(
  579. item,
  580. args[0],
  581. nested=nested - 1,
  582. treat_var_as_type=treat_var_as_type,
  583. )
  584. for item in obj
  585. )
  586. if args:
  587. from reflex.vars import Field
  588. if origin is Field:
  589. return _isinstance(
  590. obj, args[0], nested=nested, treat_var_as_type=treat_var_as_type
  591. )
  592. return isinstance(obj, get_base_class(cls))
  593. def is_dataframe(value: type) -> bool:
  594. """Check if the given value is a dataframe.
  595. Args:
  596. value: The value to check.
  597. Returns:
  598. Whether the value is a dataframe.
  599. """
  600. if is_generic_alias(value) or value == Any:
  601. return False
  602. return value.__name__ == "DataFrame"
  603. def is_valid_var_type(type_: type) -> bool:
  604. """Check if the given type is a valid prop type.
  605. Args:
  606. type_: The type to check.
  607. Returns:
  608. Whether the type is a valid prop type.
  609. """
  610. from reflex.utils import serializers
  611. if is_union(type_):
  612. return all(is_valid_var_type(arg) for arg in get_args(type_))
  613. return (
  614. _issubclass(type_, StateVar)
  615. or serializers.has_serializer(type_)
  616. or dataclasses.is_dataclass(type_)
  617. )
  618. def is_backend_base_variable(name: str, cls: type) -> bool:
  619. """Check if this variable name correspond to a backend variable.
  620. Args:
  621. name: The name of the variable to check
  622. cls: The class of the variable to check
  623. Returns:
  624. bool: The result of the check
  625. """
  626. if name in RESERVED_BACKEND_VAR_NAMES:
  627. return False
  628. if not name.startswith("_"):
  629. return False
  630. if name.startswith("__"):
  631. return False
  632. if name.startswith(f"_{cls.__name__}__"):
  633. return False
  634. # Extract the namespace of the original module if defined (dynamic substates).
  635. if callable(getattr(cls, "_get_type_hints", None)):
  636. hints = cls._get_type_hints()
  637. else:
  638. hints = get_type_hints(cls)
  639. if name in hints:
  640. hint = get_origin(hints[name])
  641. if hint == ClassVar:
  642. return False
  643. if name in cls.inherited_backend_vars:
  644. return False
  645. from reflex.vars.base import is_computed_var
  646. if name in cls.__dict__:
  647. value = cls.__dict__[name]
  648. if type(value) is classmethod:
  649. return False
  650. if callable(value):
  651. return False
  652. if isinstance(
  653. value,
  654. (
  655. types.FunctionType,
  656. property,
  657. cached_property,
  658. ),
  659. ) or is_computed_var(value):
  660. return False
  661. return True
  662. def check_type_in_allowed_types(value_type: type, allowed_types: Iterable) -> bool:
  663. """Check that a value type is found in a list of allowed types.
  664. Args:
  665. value_type: Type of value.
  666. allowed_types: Iterable of allowed types.
  667. Returns:
  668. If the type is found in the allowed types.
  669. """
  670. return get_base_class(value_type) in allowed_types
  671. def check_prop_in_allowed_types(prop: Any, allowed_types: Iterable) -> bool:
  672. """Check that a prop value is in a list of allowed types.
  673. Does the check in a way that works regardless if it's a raw value or a state Var.
  674. Args:
  675. prop: The prop to check.
  676. allowed_types: The list of allowed types.
  677. Returns:
  678. If the prop type match one of the allowed_types.
  679. """
  680. from reflex.vars import Var
  681. type_ = prop._var_type if isinstance(prop, Var) else type(prop)
  682. return type_ in allowed_types
  683. def is_encoded_fstring(value: Any) -> bool:
  684. """Check if a value is an encoded Var f-string.
  685. Args:
  686. value: The value string to check.
  687. Returns:
  688. Whether the value is an f-string
  689. """
  690. return isinstance(value, str) and constants.REFLEX_VAR_OPENING_TAG in value
  691. def validate_literal(key: str, value: Any, expected_type: type, comp_name: str):
  692. """Check that a value is a valid literal.
  693. Args:
  694. key: The prop name.
  695. value: The prop value to validate.
  696. expected_type: The expected type(literal type).
  697. comp_name: Name of the component.
  698. Raises:
  699. ValueError: When the value is not a valid literal.
  700. """
  701. from reflex.vars import Var
  702. if (
  703. is_literal(expected_type)
  704. and not isinstance(value, Var) # validating vars is not supported yet.
  705. and not is_encoded_fstring(value) # f-strings are not supported.
  706. and value not in expected_type.__args__
  707. ):
  708. allowed_values = expected_type.__args__
  709. if value not in allowed_values:
  710. allowed_value_str = ",".join(
  711. [str(v) if not isinstance(v, str) else f"'{v}'" for v in allowed_values]
  712. )
  713. value_str = f"'{value}'" if isinstance(value, str) else value
  714. raise ValueError(
  715. f"prop value for {key!s} of the `{comp_name}` component should be one of the following: {allowed_value_str}. Got {value_str} instead"
  716. )
  717. def validate_parameter_literals(func: Callable):
  718. """Decorator to check that the arguments passed to a function
  719. correspond to the correct function parameter if it (the parameter)
  720. is a literal type.
  721. Args:
  722. func: The function to validate.
  723. Returns:
  724. The wrapper function.
  725. """
  726. @wraps(func)
  727. def wrapper(*args, **kwargs):
  728. func_params = list(inspect.signature(func).parameters.items())
  729. annotations = {param[0]: param[1].annotation for param in func_params}
  730. # validate args
  731. for param, arg in zip(annotations, args, strict=False):
  732. if annotations[param] is inspect.Parameter.empty:
  733. continue
  734. validate_literal(param, arg, annotations[param], func.__name__)
  735. # validate kwargs.
  736. for key, value in kwargs.items():
  737. annotation = annotations.get(key)
  738. if not annotation or annotation is inspect.Parameter.empty:
  739. continue
  740. validate_literal(key, value, annotation, func.__name__)
  741. return func(*args, **kwargs)
  742. return wrapper
  743. # Store this here for performance.
  744. StateBases = get_base_class(StateVar)
  745. StateIterBases = get_base_class(StateIterVar)
  746. def safe_issubclass(cls: Any, cls_check: Any | tuple[Any, ...]):
  747. """Check if a class is a subclass of another class. Returns False if internal error occurs.
  748. Args:
  749. cls: The class to check.
  750. cls_check: The class to check against.
  751. Returns:
  752. Whether the class is a subclass of the other class.
  753. """
  754. try:
  755. return issubclass(cls, cls_check)
  756. except TypeError:
  757. return False
  758. def typehint_issubclass(
  759. possible_subclass: Any,
  760. possible_superclass: Any,
  761. *,
  762. treat_mutable_superclasss_as_immutable: bool = False,
  763. treat_literals_as_union_of_types: bool = True,
  764. treat_any_as_subtype_of_everything: bool = False,
  765. ) -> bool:
  766. """Check if a type hint is a subclass of another type hint.
  767. Args:
  768. possible_subclass: The type hint to check.
  769. possible_superclass: The type hint to check against.
  770. treat_mutable_superclasss_as_immutable: Whether to treat target classes as immutable.
  771. treat_literals_as_union_of_types: Whether to treat literals as a union of their types.
  772. treat_any_as_subtype_of_everything: Whether to treat Any as a subtype of everything. This is the default behavior in Python.
  773. Returns:
  774. Whether the type hint is a subclass of the other type hint.
  775. """
  776. if possible_superclass is Any:
  777. return True
  778. if possible_subclass is Any:
  779. return treat_any_as_subtype_of_everything
  780. if possible_subclass is NoReturn:
  781. return True
  782. provided_type_origin = get_origin(possible_subclass)
  783. accepted_type_origin = get_origin(possible_superclass)
  784. if provided_type_origin is None and accepted_type_origin is None:
  785. # In this case, we are dealing with a non-generic type, so we can use issubclass
  786. return issubclass(possible_subclass, possible_superclass)
  787. if treat_literals_as_union_of_types and is_literal(possible_superclass):
  788. args = get_args(possible_superclass)
  789. return any(
  790. typehint_issubclass(
  791. possible_subclass,
  792. type(arg),
  793. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  794. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  795. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  796. )
  797. for arg in args
  798. )
  799. if is_literal(possible_subclass):
  800. args = get_args(possible_subclass)
  801. return all(
  802. _isinstance(
  803. arg,
  804. possible_superclass,
  805. treat_mutable_obj_as_immutable=treat_mutable_superclasss_as_immutable,
  806. nested=2,
  807. )
  808. for arg in args
  809. )
  810. provided_type_origin = (
  811. Union if provided_type_origin is types.UnionType else provided_type_origin
  812. )
  813. accepted_type_origin = (
  814. Union if accepted_type_origin is types.UnionType else accepted_type_origin
  815. )
  816. # Get type arguments (e.g., [float, int] for dict[float, int])
  817. provided_args = get_args(possible_subclass)
  818. accepted_args = get_args(possible_superclass)
  819. if accepted_type_origin is Union:
  820. if provided_type_origin is not Union:
  821. return any(
  822. typehint_issubclass(
  823. possible_subclass,
  824. accepted_arg,
  825. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  826. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  827. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  828. )
  829. for accepted_arg in accepted_args
  830. )
  831. return all(
  832. any(
  833. typehint_issubclass(
  834. provided_arg,
  835. accepted_arg,
  836. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  837. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  838. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  839. )
  840. for accepted_arg in accepted_args
  841. )
  842. for provided_arg in provided_args
  843. )
  844. if provided_type_origin is Union:
  845. return all(
  846. typehint_issubclass(
  847. provided_arg,
  848. possible_superclass,
  849. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  850. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  851. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  852. )
  853. for provided_arg in provided_args
  854. )
  855. provided_type_origin = provided_type_origin or possible_subclass
  856. accepted_type_origin = accepted_type_origin or possible_superclass
  857. if treat_mutable_superclasss_as_immutable:
  858. if accepted_type_origin is dict:
  859. accepted_type_origin = Mapping
  860. elif accepted_type_origin is list or accepted_type_origin is set:
  861. accepted_type_origin = Sequence
  862. # Check if the origin of both types is the same (e.g., list for list[int])
  863. if not safe_issubclass(
  864. provided_type_origin or possible_subclass,
  865. accepted_type_origin or possible_superclass,
  866. ):
  867. return False
  868. # Ensure all specific types are compatible with accepted types
  869. # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
  870. # It also ignores when the length of the arguments is different
  871. return all(
  872. typehint_issubclass(
  873. provided_arg,
  874. accepted_arg,
  875. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  876. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  877. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  878. )
  879. for provided_arg, accepted_arg in zip(
  880. provided_args, accepted_args, strict=False
  881. )
  882. if accepted_arg is not Any
  883. )