types.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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. console.deprecate(
  727. "validate_parameter_literals",
  728. reason="Use manual validation instead.",
  729. deprecation_version="0.7.11",
  730. removal_version="0.8.0",
  731. dedupe=True,
  732. )
  733. func_params = list(inspect.signature(func).parameters.items())
  734. annotations = {param[0]: param[1].annotation for param in func_params}
  735. @wraps(func)
  736. def wrapper(*args, **kwargs):
  737. # validate args
  738. for param, arg in zip(annotations, args, strict=False):
  739. if annotations[param] is inspect.Parameter.empty:
  740. continue
  741. validate_literal(param, arg, annotations[param], func.__name__)
  742. # validate kwargs.
  743. for key, value in kwargs.items():
  744. annotation = annotations.get(key)
  745. if not annotation or annotation is inspect.Parameter.empty:
  746. continue
  747. validate_literal(key, value, annotation, func.__name__)
  748. return func(*args, **kwargs)
  749. return wrapper
  750. # Store this here for performance.
  751. StateBases = get_base_class(StateVar)
  752. StateIterBases = get_base_class(StateIterVar)
  753. def safe_issubclass(cls: Any, cls_check: Any | tuple[Any, ...]):
  754. """Check if a class is a subclass of another class. Returns False if internal error occurs.
  755. Args:
  756. cls: The class to check.
  757. cls_check: The class to check against.
  758. Returns:
  759. Whether the class is a subclass of the other class.
  760. """
  761. try:
  762. return issubclass(cls, cls_check)
  763. except TypeError:
  764. return False
  765. def typehint_issubclass(
  766. possible_subclass: Any,
  767. possible_superclass: Any,
  768. *,
  769. treat_mutable_superclasss_as_immutable: bool = False,
  770. treat_literals_as_union_of_types: bool = True,
  771. treat_any_as_subtype_of_everything: bool = False,
  772. ) -> bool:
  773. """Check if a type hint is a subclass of another type hint.
  774. Args:
  775. possible_subclass: The type hint to check.
  776. possible_superclass: The type hint to check against.
  777. treat_mutable_superclasss_as_immutable: Whether to treat target classes as immutable.
  778. treat_literals_as_union_of_types: Whether to treat literals as a union of their types.
  779. treat_any_as_subtype_of_everything: Whether to treat Any as a subtype of everything. This is the default behavior in Python.
  780. Returns:
  781. Whether the type hint is a subclass of the other type hint.
  782. """
  783. if possible_superclass is Any:
  784. return True
  785. if possible_subclass is Any:
  786. return treat_any_as_subtype_of_everything
  787. if possible_subclass is NoReturn:
  788. return True
  789. provided_type_origin = get_origin(possible_subclass)
  790. accepted_type_origin = get_origin(possible_superclass)
  791. if provided_type_origin is None and accepted_type_origin is None:
  792. # In this case, we are dealing with a non-generic type, so we can use issubclass
  793. return issubclass(possible_subclass, possible_superclass)
  794. if treat_literals_as_union_of_types and is_literal(possible_superclass):
  795. args = get_args(possible_superclass)
  796. return any(
  797. typehint_issubclass(
  798. possible_subclass,
  799. type(arg),
  800. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  801. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  802. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  803. )
  804. for arg in args
  805. )
  806. if is_literal(possible_subclass):
  807. args = get_args(possible_subclass)
  808. return all(
  809. _isinstance(
  810. arg,
  811. possible_superclass,
  812. treat_mutable_obj_as_immutable=treat_mutable_superclasss_as_immutable,
  813. nested=2,
  814. )
  815. for arg in args
  816. )
  817. provided_type_origin = (
  818. Union if provided_type_origin is types.UnionType else provided_type_origin
  819. )
  820. accepted_type_origin = (
  821. Union if accepted_type_origin is types.UnionType else accepted_type_origin
  822. )
  823. # Get type arguments (e.g., [float, int] for dict[float, int])
  824. provided_args = get_args(possible_subclass)
  825. accepted_args = get_args(possible_superclass)
  826. if accepted_type_origin is Union:
  827. if provided_type_origin is not Union:
  828. return any(
  829. typehint_issubclass(
  830. possible_subclass,
  831. accepted_arg,
  832. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  833. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  834. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  835. )
  836. for accepted_arg in accepted_args
  837. )
  838. return all(
  839. any(
  840. typehint_issubclass(
  841. provided_arg,
  842. accepted_arg,
  843. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  844. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  845. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  846. )
  847. for accepted_arg in accepted_args
  848. )
  849. for provided_arg in provided_args
  850. )
  851. if provided_type_origin is Union:
  852. return all(
  853. typehint_issubclass(
  854. provided_arg,
  855. possible_superclass,
  856. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  857. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  858. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  859. )
  860. for provided_arg in provided_args
  861. )
  862. provided_type_origin = provided_type_origin or possible_subclass
  863. accepted_type_origin = accepted_type_origin or possible_superclass
  864. if treat_mutable_superclasss_as_immutable:
  865. if accepted_type_origin is dict:
  866. accepted_type_origin = Mapping
  867. elif accepted_type_origin is list or accepted_type_origin is set:
  868. accepted_type_origin = Sequence
  869. # Check if the origin of both types is the same (e.g., list for list[int])
  870. if not safe_issubclass(
  871. provided_type_origin or possible_subclass,
  872. accepted_type_origin or possible_superclass,
  873. ):
  874. return False
  875. # Ensure all specific types are compatible with accepted types
  876. # Note this is not necessarily correct, as it doesn't check against contravariance and covariance
  877. # It also ignores when the length of the arguments is different
  878. return all(
  879. typehint_issubclass(
  880. provided_arg,
  881. accepted_arg,
  882. treat_mutable_superclasss_as_immutable=treat_mutable_superclasss_as_immutable,
  883. treat_literals_as_union_of_types=treat_literals_as_union_of_types,
  884. treat_any_as_subtype_of_everything=treat_any_as_subtype_of_everything,
  885. )
  886. for provided_arg, accepted_arg in zip(
  887. provided_args, accepted_args, strict=False
  888. )
  889. if accepted_arg is not Any
  890. )