def __new__(
        cls,
        func: Callable[[BASE_STATE, Unpack[P]], Any] | None = None,
        *,
        background: bool | None = None,
    ) -> (
        EventCallback[Unpack[P]]
        | Callable[[Callable[[BASE_STATE, Unpack[P]], Any]], EventCallback[Unpack[P]]]
    ):
        """Wrap a function to be used as an event.

        Args:
            func: The function to wrap.
            background: Whether the event should be run in the background. Defaults to False.

        Raises:
            TypeError: If background is True and the function is not a coroutine or async generator. # noqa: DAR402

        Returns:
            The wrapped function.
        """

        def wrapper(
            func: Callable[[BASE_STATE, Unpack[P]], T],
        ) -> EventCallback[Unpack[P]]:
            if background is True:
                if not inspect.iscoroutinefunction(
                    func
                ) and not inspect.isasyncgenfunction(func):
                    msg = "Background task must be async function or generator."
                    raise TypeError(msg)
                setattr(func, BACKGROUND_TASK_MARKER, True)
            if getattr(func, "__name__", "").startswith("_"):
                msg = "Event handlers cannot be private."
                raise ValueError(msg)

            qualname: str | None = getattr(func, "__qualname__", None)

            if qualname and (
                len(func_path := qualname.split(".")) == 1
                or func_path[-2] == "<locals>"
            ):
                from reflex.state import BaseState

                types = get_type_hints(func)
                state_arg_name = next(iter(inspect.signature(func).parameters), None)
                state_cls = state_arg_name and types.get(state_arg_name)
                if state_cls and issubclass(state_cls, BaseState):
                    name = (
                        (func.__module__ + "." + qualname)
                        .replace(".", "_")
                        .replace("<locals>", "_")
                        .removeprefix("_")
                    )
                    object.__setattr__(func, "__name__", name)
                    object.__setattr__(func, "__qualname__", name)
                    state_cls._add_event_handler(name, func)
                    return getattr(state_cls, name)

            return func  # pyright: ignore [reportReturnType]

        if func is not None:
            return wrapper(func)
        return wrapper
Wrap a function to be used as an event.

        Args:
            func: The function to wrap.
            background: Whether the event should be run in the background. Defaults to False.

        Raises:
            TypeError: If background is True and the function is not a coroutine or async generator. # noqa: DAR402

        Returns:
            The wrapped function.
        
reflex/event.py