types.py 33 KB

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