Protocol for event handlers is too restrictive
- Dominant language
- Python
- Stars
- 5.4k
- Forks
- 827
- Avg merge
- 9h 45m
- Merged PRs (30d)
- 58
Description
### Describe the bug
The `BackgroundTask` protocol only defines support for normal functions and methods. The code, however, allows background tasks to be a `NativeHandler`, coroutine, or generator.
```Python
class BackgroundTask(Protocol):
def __call__(self, app: App, **kwargs: Any) -> None: ...
```
### Steps to reproduce
Run `mypy --strict` against the app below:
```python
import asyncio
from typing import Any
import toga
class AutoExit(toga.App):
async def exit_soon(self, app: toga.App, **kwargs: Any) -> None:
await asyncio.sleep(3)
print(">>> successfully started...exiting <<<")
self.exit()
def startup(self) -> None:
"""Show the Toga application."""
self.add_background_task(self.exit_soon)
main_box = toga.Box()
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show()
def main() -> AutoExit:
return AutoExit()
```
```console
❯ mypy --strict src/plugintesting/app.py
src/plugintesting/app.py:19: error: Argument 1 to "add_background_task" of "App" has incompatible type "Callable[[App, KwArg(Any)], Coroutine[Any, Any, None]]"; expected "BackgroundTask" [arg-type]
Found 1 error in 1 file (checked 1 source file)
```
### Expected behavior
This protocol accurately represents the objects that can be passed to `add_background_task()`.
Note: Other handler protocols may be affected; I just wanted to document this one while I was seeing it.
### Screenshots
_No response_
### Environment
- Operating System: pop os 22.04
- Python version: 3.10.13
- Software versions:
- Briefcase: `0.3.17.dev45+g8e412970.d20231104`
- Toga: `0.4.0`
### Logs
_No response_
### Additional context
- https://github.com/beeware/toga/issues/2042
Contributor guide
Research direction
Start by locating the BackgroundTask protocol and add_background_task() definition, then inspect how NativeHandler, coroutines, and generators are handled. Update the relevant typing definitions and check the provided mypy --strict example, along with any affected handler protocols; done means supported handlers type-check without weakening unrelated checks.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- developer-experience
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100