Convert a component to a Component. Args: component: The component to convert. Returns: The converted component. Raises: TypeError: If the component is not a Component. # noqa: DAR401
(component: Component | ComponentCallable)
| 842 | |
| 843 | |
| 844 | def into_component(component: Component | ComponentCallable) -> Component: |
| 845 | """Convert a component to a Component. |
| 846 | |
| 847 | Args: |
| 848 | component: The component to convert. |
| 849 | |
| 850 | Returns: |
| 851 | The converted component. |
| 852 | |
| 853 | Raises: |
| 854 | TypeError: If the component is not a Component. |
| 855 | |
| 856 | # noqa: DAR401 |
| 857 | """ |
| 858 | if (converted := _into_component_once(component)) is not None: |
| 859 | return converted |
| 860 | if not callable(component): |
| 861 | msg = f"Expected a Component or callable, got {component!r} of type {type(component)}" |
| 862 | raise TypeError(msg) |
| 863 | |
| 864 | try: |
| 865 | component_called = component() |
| 866 | except KeyError as e: |
| 867 | if isinstance(e, ReflexError): |
| 868 | _modify_exception(e) |
| 869 | raise |
| 870 | key = e.args[0] if e.args else None |
| 871 | if key is not None and isinstance(key, Var): |
| 872 | raise TypeError( |
| 873 | "Cannot access a primitive map with a Var. Consider calling rx.Var.create() on the map." |
| 874 | ).with_traceback(e.__traceback__) from None |
| 875 | raise |
| 876 | except TypeError as e: |
| 877 | if isinstance(e, ReflexError): |
| 878 | _modify_exception(e) |
| 879 | raise |
| 880 | message = e.args[0] if e.args else None |
| 881 | if message and isinstance(message, str): |
| 882 | if message.endswith("has no len()") and ( |
| 883 | "ArrayCastedVar" in message |
| 884 | or "ObjectCastedVar" in message |
| 885 | or "StringCastedVar" in message |
| 886 | ): |
| 887 | raise TypeError( |
| 888 | "Cannot pass a Var to a built-in function. Consider using .length() for accessing the length of an iterable Var." |
| 889 | ).with_traceback(e.__traceback__) from None |
| 890 | if message.endswith(( |
| 891 | "indices must be integers or slices, not NumberCastedVar", |
| 892 | "indices must be integers or slices, not BooleanCastedVar", |
| 893 | )): |
| 894 | raise TypeError( |
| 895 | "Cannot index into a primitive sequence with a Var. Consider calling rx.Var.create() on the sequence." |
| 896 | ).with_traceback(e.__traceback__) from None |
| 897 | if "CastedVar" in str(e): |
| 898 | raise TypeError( |
| 899 | "Cannot pass a Var to a built-in function. Consider moving the operation to the backend, using existing Var operations, or defining a custom Var operation." |
| 900 | ).with_traceback(e.__traceback__) from None |
| 901 | raise |
no test coverage detected