Skip to content

WorkType alias too restrictive for async def functions #6386

@fieldjoshua

Description

@fieldjoshua

Description

WorkType in textual/worker.py is defined as:

WorkType: TypeAlias = Union[
    Callable[[], Coroutine[None, None, ResultType]],
    Callable[[], ResultType],
    Awaitable[ResultType],
]

Python's async def always produces Coroutine[Any, Any, ReturnType], not Coroutine[None, None, ReturnType]. This means every async def method passed to run_worker fails mypy strict checking:

error: Argument 1 to "run_worker" of "DOMNode" has incompatible type
"Callable[[], Coroutine[Any, Any, None]]";
expected "Callable[[], Coroutine[None, None, Never]] | Callable[[], Never] | Awaitable[Never]"

Reproduction

from textual.app import App, ComposeResult
from textual.widgets import Static

class MyApp(App):
    def compose(self) -> ComposeResult:
        yield Static("hello")

    def on_mount(self) -> None:
        self.run_worker(self._do_work)  # mypy error here

    async def _do_work(self) -> None:
        pass

Run mypy with strict mode and this fails.

Suggested fix

WorkType: TypeAlias = Union[
    Callable[[], Coroutine[Any, Any, ResultType]],
    Callable[[], ResultType],
    Awaitable[ResultType],
]

Environment

  • Textual 8.0.0
  • Python 3.12
  • mypy 1.15.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions