types.py 29 KB

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