types.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. """Contains custom types and methods to check types."""
  2. from __future__ import annotations
  3. import dataclasses
  4. import inspect
  5. import sys
  6. import types
  7. from functools import cached_property, lru_cache, wraps
  8. from types import GenericAlias
  9. from typing import (
  10. TYPE_CHECKING,
  11. Any,
  12. Callable,
  13. ClassVar,
  14. Dict,
  15. ForwardRef,
  16. FrozenSet,
  17. Iterable,
  18. List,
  19. Literal,
  20. Mapping,
  21. NoReturn,
  22. Optional,
  23. Sequence,
  24. Tuple,
  25. Type,
  26. Union,
  27. _GenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  28. _SpecialGenericAlias, # pyright: ignore [reportAttributeAccessIssue]
  29. get_args,
  30. )
  31. from typing import get_origin as get_origin_og
  32. from typing import get_type_hints as get_type_hints_og
  33. import sqlalchemy
  34. from pydantic.v1.fields import ModelField
  35. from sqlalchemy.ext.associationproxy import AssociationProxyInstance
  36. from sqlalchemy.ext.hybrid import hybrid_property
  37. from sqlalchemy.orm import DeclarativeBase, Mapped, QueryableAttribute, Relationship
  38. from typing_extensions import Self as Self
  39. from typing_extensions import is_typeddict
  40. from typing_extensions import override as override
  41. import reflex
  42. from reflex import constants
  43. from reflex.base import Base
  44. from reflex.components.core.breakpoints import Breakpoints
  45. from reflex.utils import console
  46. # Potential GenericAlias types for isinstance checks.
  47. GenericAliasTypes = (_GenericAlias, GenericAlias, _SpecialGenericAlias)
  48. # Potential Union types for isinstance checks.
  49. UnionTypes = (Union, types.UnionType)
  50. # Union of generic types.
  51. GenericType = Type | _GenericAlias
  52. # Valid state var types.
  53. JSONType = {str, int, float, bool}
  54. PrimitiveType = Union[int, float, bool, str, list, dict, set, tuple]
  55. PrimitiveTypes = (int, float, bool, str, list, dict, set, tuple)
  56. StateVar = PrimitiveType | Base | None
  57. StateIterVar = list | set | tuple
  58. if TYPE_CHECKING:
  59. from reflex.vars.base import Var
  60. ArgsSpec = (
  61. Callable[[], Sequence[Var]]
  62. | Callable[[Var], Sequence[Var]]
  63. | Callable[[Var, Var], Sequence[Var]]
  64. | Callable[[Var, Var, Var], Sequence[Var]]
  65. | Callable[[Var, Var, Var, Var], Sequence[Var]]
  66. | Callable[[Var, Var, Var, Var, Var], Sequence[Var]]
  67. | Callable[[Var, Var, Var, Var, Var, Var], Sequence[Var]]
  68. | Callable[[Var, Var, Var, Var, Var, Var, Var], Sequence[Var]]
  69. )
  70. else:
  71. ArgsSpec = Callable[..., list[Any]]
  72. PrimitiveToAnnotation = {
  73. list: List,
  74. tuple: Tuple,
  75. dict: Dict,
  76. }
  77. RESERVED_BACKEND_VAR_NAMES = {
  78. "_abc_impl",
  79. "_backend_vars",
  80. "_was_touched",
  81. }
  82. class Unset:
  83. """A class to represent an unset value.
  84. This is used to differentiate between a value that is not set and a value that is set to None.
  85. """
  86. def __repr__(self) -> str:
  87. """Return the string representation of the class.
  88. Returns:
  89. The string representation of the class.
  90. """
  91. return "Unset"
  92. def __bool__(self) -> bool:
  93. """Return False when the class is used in a boolean context.
  94. Returns:
  95. False
  96. """
  97. return False
  98. @lru_cache()
  99. def get_origin(tp: Any):
  100. """Get the origin of a class.
  101. Args:
  102. tp: The class to get the origin of.
  103. Returns:
  104. The origin of the class.
  105. """
  106. return get_origin_og(tp)
  107. @lru_cache()
  108. def is_generic_alias(cls: GenericType) -> bool:
  109. """Check whether the class is a generic alias.
  110. Args:
  111. cls: The class to check.
  112. Returns:
  113. Whether the class is a generic alias.
  114. """
  115. return isinstance(cls, GenericAliasTypes)
  116. @lru_cache()
  117. def get_type_hints(obj: Any) -> Dict[str, Any]:
  118. """Get the type hints of a class.
  119. Args:
  120. obj: The class to get the type hints of.
  121. Returns:
  122. The type hints of the class.
  123. """
  124. return get_type_hints_og(obj)
  125. def _unionize(args: list[GenericType]) -> Type:
  126. if not args:
  127. return Any # pyright: ignore [reportReturnType]
  128. if len(args) == 1:
  129. return args[0]
  130. # We are bisecting the args list here to avoid hitting the recursion limit
  131. # In Python versions >= 3.11, we can simply do `return Union[*args]`
  132. midpoint = len(args) // 2
  133. first_half, second_half = args[:midpoint], args[midpoint:]
  134. return Union[unionize(*first_half), unionize(*second_half)] # pyright: ignore [reportReturnType]
  135. def unionize(*args: GenericType) -> Type:
  136. """Unionize the types.
  137. Args:
  138. args: The types to unionize.
  139. Returns:
  140. The unionized types.
  141. """
  142. return _unionize([arg for arg in args if arg is not NoReturn])
  143. def is_none(cls: GenericType) -> bool:
  144. """Check if a class is None.
  145. Args:
  146. cls: The class to check.
  147. Returns:
  148. Whether the class is None.
  149. """
  150. return cls is type(None) or cls is None
  151. @lru_cache()
  152. def is_union(cls: GenericType) -> bool:
  153. """Check if a class is a Union.
  154. Args:
  155. cls: The class to check.
  156. Returns:
  157. Whether the class is a Union.
  158. """
  159. return get_origin(cls) in UnionTypes
  160. @lru_cache()
  161. def is_literal(cls: GenericType) -> bool:
  162. """Check if a class is a Literal.
  163. Args:
  164. cls: The class to check.
  165. Returns:
  166. Whether the class is a literal.
  167. """
  168. return get_origin(cls) is Literal
  169. def has_args(cls: Type) -> bool:
  170. """Check if the class has generic parameters.
  171. Args:
  172. cls: The class to check.
  173. Returns:
  174. Whether the class has generic
  175. """
  176. if get_args(cls):
  177. return True
  178. # Check if the class inherits from a generic class (using __orig_bases__)
  179. if hasattr(cls, "__orig_bases__"):
  180. for base in cls.__orig_bases__:
  181. if get_args(base):
  182. return True
  183. return False
  184. def is_optional(cls: GenericType) -> bool:
  185. """Check if a class is an Optional.
  186. Args:
  187. cls: The class to check.
  188. Returns:
  189. Whether the class is an Optional.
  190. """
  191. return is_union(cls) and type(None) in get_args(cls)
  192. def true_type_for_pydantic_field(f: ModelField):
  193. """Get the type for a pydantic field.
  194. Args:
  195. f: The field to get the type for.
  196. Returns:
  197. The type for the field.
  198. """
  199. if not isinstance(f.annotation, (str, ForwardRef)):
  200. return f.annotation
  201. type_ = f.outer_type_
  202. if (
  203. f.field_info.default is None
  204. or (isinstance(f.annotation, str) and f.annotation.startswith("Optional"))
  205. or (
  206. isinstance(f.annotation, ForwardRef)
  207. and f.annotation.__forward_arg__.startswith("Optional")
  208. )
  209. ) and not is_optional(type_):
  210. return Optional[type_]
  211. return type_
  212. def value_inside_optional(cls: GenericType) -> GenericType:
  213. """Get the value inside an Optional type or the original type.
  214. Args:
  215. cls: The class to check.
  216. Returns:
  217. The value inside the Optional type or the original type.
  218. """
  219. if is_union(cls) and len(args := get_args(cls)) >= 2 and type(None) in args:
  220. if len(args) == 2:
  221. return args[0] if args[1] is type(None) else args[1]
  222. return unionize(*[arg for arg in args if arg is not type(None)])
  223. return cls
  224. def get_field_type(cls: GenericType, field_name: str) -> GenericType | None:
  225. """Get the type of a field in a class.
  226. Args:
  227. cls: The class to check.
  228. field_name: The name of the field to check.
  229. Returns:
  230. The type of the field, if it exists, else None.
  231. """
  232. if (
  233. hasattr(cls, "__fields__")
  234. and field_name in cls.__fields__
  235. and hasattr(cls.__fields__[field_name], "annotation")
  236. and not isinstance(cls.__fields__[field_name].annotation, (str, ForwardRef))
  237. ):
  238. return cls.__fields__[field_name].annotation
  239. type_hints = get_type_hints(cls)
  240. return type_hints.get(field_name, None)
  241. def get_property_hint(attr: Any | None) -> GenericType | None:
  242. """Check if an attribute is a property and return its type hint.
  243. Args:
  244. attr: The descriptor to check.
  245. Returns:
  246. The type hint of the property, if it is a property, else None.
  247. """
  248. if not isinstance(attr, (property, hybrid_property)):
  249. return None
  250. hints = get_type_hints(attr.fget)
  251. return hints.get("return", None)
  252. def get_attribute_access_type(cls: GenericType, name: str) -> GenericType | None:
  253. """Check if an attribute can be accessed on the cls and return its type.
  254. Supports pydantic models, unions, and annotated attributes on rx.Model.
  255. Args:
  256. cls: The class to check.
  257. name: The name of the attribute to check.
  258. Returns:
  259. The type of the attribute, if accessible, or None
  260. """
  261. from reflex.model import Model
  262. try:
  263. attr = getattr(cls, name, None)
  264. except NotImplementedError:
  265. attr = None
  266. if hint := get_property_hint(attr):
  267. return hint
  268. if hasattr(cls, "__fields__") and name in cls.__fields__:
  269. # pydantic models
  270. return get_field_type(cls, name)
  271. elif isinstance(cls, type) and issubclass(cls, DeclarativeBase):
  272. insp = sqlalchemy.inspect(cls)
  273. if name in insp.columns:
  274. # check for list types
  275. column = insp.columns[name]
  276. column_type = column.type
  277. try:
  278. type_ = insp.columns[name].type.python_type
  279. except NotImplementedError:
  280. type_ = None
  281. if type_ is not None:
  282. if hasattr(column_type, "item_type"):
  283. try:
  284. item_type = column_type.item_type.python_type # pyright: ignore [reportAttributeAccessIssue]
  285. except NotImplementedError:
  286. item_type = None
  287. if item_type is not None:
  288. if type_ in PrimitiveToAnnotation:
  289. type_ = PrimitiveToAnnotation[type_]
  290. type_ = type_[item_type] # pyright: ignore [reportIndexIssue]
  291. if column.nullable:
  292. type_ = type_ | None
  293. return type_
  294. if name in insp.all_orm_descriptors:
  295. descriptor = insp.all_orm_descriptors[name]
  296. if hint := get_property_hint(descriptor):
  297. return hint
  298. if isinstance(descriptor, QueryableAttribute):
  299. prop = descriptor.property
  300. if isinstance(prop, Relationship):
  301. type_ = prop.mapper.class_
  302. # TODO: check for nullable?
  303. type_ = list[type_] if prop.uselist else type_ | None
  304. return type_
  305. if isinstance(attr, AssociationProxyInstance):
  306. return list[
  307. get_attribute_access_type(
  308. attr.target_class,
  309. attr.remote_attr.key, # type: ignore[attr-defined]
  310. )
  311. ]
  312. elif isinstance(cls, type) and not is_generic_alias(cls) and issubclass(cls, Model):
  313. # Check in the annotations directly (for sqlmodel.Relationship)
  314. hints = get_type_hints(cls)
  315. if name in hints:
  316. type_ = hints[name]
  317. type_origin = get_origin(type_)
  318. if isinstance(type_origin, type) and issubclass(type_origin, Mapped):
  319. return get_args(type_)[0] # SQLAlchemy v2
  320. if isinstance(type_, ModelField):
  321. return type_.type_ # SQLAlchemy v1.4
  322. return type_
  323. elif is_union(cls):
  324. # Check in each arg of the annotation.
  325. return unionize(
  326. *(get_attribute_access_type(arg, name) for arg in get_args(cls))
  327. )
  328. elif isinstance(cls, type):
  329. # Bare class
  330. if sys.version_info >= (3, 10):
  331. exceptions = NameError
  332. else:
  333. exceptions = (NameError, TypeError)
  334. try:
  335. hints = get_type_hints(cls)
  336. if name in hints:
  337. return hints[name]
  338. except exceptions as e:
  339. console.warn(f"Failed to resolve ForwardRefs for {cls}.{name} due to {e}")
  340. pass
  341. return None # Attribute is not accessible.
  342. @lru_cache()
  343. def get_base_class(cls: GenericType) -> Type:
  344. """Get the base class of a class.
  345. Args:
  346. cls: The class.
  347. Returns:
  348. The base class of the class.
  349. Raises:
  350. TypeError: If a literal has multiple types.
  351. """
  352. if is_literal(cls):
  353. # only literals of the same type are supported.
  354. arg_type = type(get_args(cls)[0])
  355. if not all(type(arg) is arg_type for arg in get_args(cls)):
  356. raise TypeError("only literals of the same type are supported")
  357. return type(get_args(cls)[0])
  358. if is_union(cls):
  359. return tuple(get_base_class(arg) for arg in get_args(cls)) # pyright: ignore [reportReturnType]
  360. return get_base_class(cls.__origin__) if is_generic_alias(cls) else cls
  361. def _breakpoints_satisfies_typing(cls_check: GenericType, instance: Any) -> bool:
  362. """Check if the breakpoints instance satisfies the typing.
  363. Args:
  364. cls_check: The class to check against.
  365. instance: The instance to check.
  366. Returns:
  367. Whether the breakpoints instance satisfies the typing.
  368. """
  369. cls_check_base = get_base_class(cls_check)
  370. if cls_check_base == Breakpoints:
  371. _, expected_type = get_args(cls_check)
  372. if is_literal(expected_type):
  373. for value in instance.values():
  374. if not isinstance(value, str) or value not in get_args(expected_type):
  375. return False
  376. return True
  377. elif isinstance(cls_check_base, tuple):
  378. # union type, so check all types
  379. return any(
  380. _breakpoints_satisfies_typing(type_to_check, instance)
  381. for type_to_check in get_args(cls_check)
  382. )
  383. elif cls_check_base == reflex.vars.Var and "__args__" in cls_check.__dict__:
  384. return _breakpoints_satisfies_typing(get_args(cls_check)[0], instance)
  385. return False
  386. def _issubclass(cls: GenericType, cls_check: GenericType, instance: Any = None) -> bool:
  387. """Check if a class is a subclass of another class.
  388. Args:
  389. cls: The class to check.
  390. cls_check: The class to check against.
  391. instance: An instance of cls to aid in checking generics.
  392. Returns:
  393. Whether the class is a subclass of the other class.
  394. Raises:
  395. TypeError: If the base class is not valid for issubclass.
  396. """
  397. # Special check for Any.
  398. if cls_check == Any:
  399. return True
  400. if cls in [Any, Callable, None]:
  401. return False
  402. # Get the base classes.
  403. cls_base = get_base_class(cls)
  404. cls_check_base = get_base_class(cls_check)
  405. # The class we're checking should not be a union.
  406. if isinstance(cls_base, tuple):
  407. return False
  408. # Check that fields of breakpoints match the expected values.
  409. if isinstance(instance, Breakpoints):
  410. return _breakpoints_satisfies_typing(cls_check, instance)
  411. if isinstance(cls_check_base, tuple):
  412. cls_check_base = tuple(
  413. cls_check_one if not is_typeddict(cls_check_one) else dict
  414. for cls_check_one in cls_check_base
  415. )
  416. if is_typeddict(cls_check_base):
  417. cls_check_base = dict
  418. # Check if the types match.
  419. try:
  420. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  421. except TypeError as te:
  422. # These errors typically arise from bad annotations and are hard to
  423. # debug without knowing the type that we tried to compare.
  424. raise TypeError(f"Invalid type for issubclass: {cls_base}") from te
  425. def does_obj_satisfy_typed_dict(obj: Any, cls: GenericType) -> bool:
  426. """Check if an object satisfies a typed dict.
  427. Args:
  428. obj: The object to check.
  429. cls: The typed dict to check against.
  430. Returns:
  431. Whether the object satisfies the typed dict.
  432. """
  433. if not isinstance(obj, Mapping):
  434. return False
  435. key_names_to_values = get_type_hints(cls)
  436. required_keys: FrozenSet[str] = getattr(cls, "__required_keys__", frozenset())
  437. if not all(
  438. isinstance(key, str)
  439. and key in key_names_to_values
  440. and _isinstance(value, key_names_to_values[key])
  441. for key, value in obj.items()
  442. ):
  443. return False
  444. # TODO in 3.14: Implement https://peps.python.org/pep-0728/ if it's approved
  445. # required keys are all present
  446. return required_keys.issubset(required_keys)
  447. def _isinstance(
  448. obj: Any,
  449. cls: GenericType,
  450. *,
  451. nested: int = 0,
  452. treat_var_as_type: bool = True,
  453. treat_mutable_obj_as_immutable: bool = False,
  454. ) -> bool:
  455. """Check if an object is an instance of a class.
  456. Args:
  457. obj: The object to check.
  458. cls: The class to check against.
  459. nested: How many levels deep to check.
  460. treat_var_as_type: Whether to treat Var as the type it represents, i.e. _var_type.
  461. treat_mutable_obj_as_immutable: Whether to treat mutable objects as immutable. Useful if a component declares a mutable object as a prop, but the value is not expected to change.
  462. Returns:
  463. Whether the object is an instance of the class.
  464. """
  465. if cls is Any:
  466. return True
  467. from reflex.vars import LiteralVar, Var
  468. if cls is Var:
  469. return isinstance(obj, Var)
  470. if isinstance(obj, LiteralVar):
  471. return treat_var_as_type and _isinstance(
  472. obj._var_value, cls, nested=nested, treat_var_as_type=True
  473. )
  474. if isinstance(obj, Var):
  475. return treat_var_as_type and typehint_issubclass(
  476. obj._var_type,
  477. cls,
  478. treat_mutable_superclasss_as_immutable=treat_mutable_obj_as_immutable,
  479. treat_literals_as_union_of_types=True,
  480. treat_any_as_subtype_of_everything=True,
  481. )
  482. if cls is None or cls is type(None):
  483. return obj is None
  484. if cls 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. # Remove this check when Python 3.10 is the minimum supported version
  800. if hasattr(types, "UnionType"):
  801. provided_type_origin = (
  802. Union if provided_type_origin is types.UnionType else provided_type_origin
  803. )
  804. accepted_type_origin = (
  805. Union if accepted_type_origin is types.UnionType else accepted_type_origin
  806. )
  807. # Get type arguments (e.g., [float, int] for dict[float, int])
  808. provided_args = get_args(possible_subclass)
  809. accepted_args = get_args(possible_superclass)
  810. if accepted_type_origin is Union:
  811. if provided_type_origin is not Union:
  812. return any(
  813. typehint_issubclass(
  814. possible_subclass,
  815. accepted_arg,
  816. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  817. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  818. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  819. )
  820. for accepted_arg in accepted_args
  821. )
  822. return all(
  823. any(
  824. typehint_issubclass(
  825. provided_arg,
  826. accepted_arg,
  827. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  828. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  829. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  830. )
  831. for accepted_arg in accepted_args
  832. )
  833. for provided_arg in provided_args
  834. )
  835. if provided_type_origin is Union:
  836. return all(
  837. typehint_issubclass(
  838. provided_arg,
  839. possible_superclass,
  840. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  841. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  842. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  843. )
  844. for provided_arg in provided_args
  845. )
  846. provided_type_origin = provided_type_origin or possible_subclass
  847. accepted_type_origin = accepted_type_origin or possible_superclass
  848. if treat_mutable_superclasss_as_immutable:
  849. if accepted_type_origin is dict:
  850. accepted_type_origin = Mapping
  851. elif accepted_type_origin is list or accepted_type_origin is set:
  852. accepted_type_origin = Sequence
  853. # Check if the origin of both types is the same (e.g., list for list[int])
  854. if not safe_issubclass(
  855. provided_type_origin or possible_subclass,
  856. accepted_type_origin or possible_superclass,
  857. ):
  858. return False
  859. # Ensure all specific types are compatible with accepted types
  860. # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
  861. # It also ignores when the length of the arguments is different
  862. return all(
  863. typehint_issubclass(
  864. provided_arg,
  865. accepted_arg,
  866. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  867. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  868. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  869. )
  870. for provided_arg, accepted_arg in zip(
  871. provided_args, accepted_args, strict=False
  872. )
  873. if accepted_arg is not Any
  874. )