Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions typer/main.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import asyncio
import inspect
import os
import platform
import shutil
import subprocess
import sys
import traceback
from collections.abc import Callable, Sequence
from functools import update_wrapper
from collections.abc import Awaitable, Callable, Sequence
from functools import update_wrapper, wraps
from traceback import FrameSummary, StackSummary
from types import TracebackType
from typing import Annotated, Any
from typing import Annotated, Any, ParamSpec, TypeVar

from annotated_doc import Doc

Expand Down Expand Up @@ -45,6 +46,8 @@

_original_except_hook = sys.excepthook
_typer_developer_exception_attr_name = "__typer_developer_exception__"
_P = ParamSpec("_P")
_T = TypeVar("_T")


def except_hook(
Expand Down Expand Up @@ -98,6 +101,16 @@ def except_hook(
return


def wrap_async_command(
app: "Typer", func: Callable[_P, Awaitable[_T]]
) -> Callable[_P, _T]:
@wraps(func)
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
return app.async_runner.run(func(*args, **kwargs))

return wrapper


def get_install_completion_arguments() -> tuple[_click.Parameter, _click.Parameter]:
install_param, show_param = get_completion_inspect_parameters()
click_install_param = _get_param(install_param)
Expand Down Expand Up @@ -505,6 +518,10 @@ def callback():
"""
),
] = True,
loop_factory: Annotated[
asyncio.AbstractEventLoop | None,
Doc("Adds customizable event loop execution for commands and callbacks"),
] = None,
):
self._add_completion = add_completion
self.rich_markup_mode: MarkupMode = rich_markup_mode
Expand Down Expand Up @@ -534,6 +551,8 @@ def callback():
self.registered_groups: list[TyperInfo] = []
self.registered_commands: list[CommandInfo] = []
self.registered_callback: TyperInfo | None = None
self.loop_factory = loop_factory
self.async_runner = asyncio.Runner(loop_factory=loop_factory)

def callback(
self,
Expand Down Expand Up @@ -715,6 +734,12 @@ def delete(username: str):
"""

def decorator(f: CommandFunctionType) -> CommandFunctionType:
# Do not alter the original function instead alias
# the newly wrapped function.
if inspect.iscoroutinefunction(f):
callback = wrap_async_command(self, f)
else:
callback = f
self.registered_callback = TyperInfo(
cls=cls,
invoke_without_command=invoke_without_command,
Expand All @@ -723,7 +748,7 @@ def decorator(f: CommandFunctionType) -> CommandFunctionType:
chain=chain,
result_callback=result_callback,
context_settings=context_settings,
callback=f,
callback=callback,
help=help,
epilog=epilog,
short_help=short_help,
Expand Down Expand Up @@ -877,12 +902,17 @@ def delete():
cls = TyperCommand

def decorator(f: CommandFunctionType) -> CommandFunctionType:
if inspect.iscoroutinefunction(f):
callback = wrap_async_command(self, f)
else:
callback = f

self.registered_commands.append(
CommandInfo(
name=name,
cls=cls,
context_settings=context_settings,
callback=f,
callback=callback,
help=help,
epilog=epilog,
short_help=short_help,
Expand Down Expand Up @@ -1123,7 +1153,8 @@ def __call__(self, *args: Any, **kwargs: Any) -> Any:
if sys.excepthook != except_hook:
sys.excepthook = except_hook
try:
return get_command(self)(*args, **kwargs)
with self.async_runner:
return get_command(self)(*args, **kwargs)
except Exception as e:
# Set a custom attribute to tell the hook to show nice exceptions for user
# code. An alternative/first implementation was a custom exception with
Expand Down
Loading