-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallable.py
More file actions
41 lines (22 loc) · 935 Bytes
/
callable.py
File metadata and controls
41 lines (22 loc) · 935 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from collections.abc import Callable
from collections.abc import Iterable
from typing import Protocol
def do_thing(on_success: Callable[[int], bool]) -> None: ...
def _success(x: int) -> bool:
return True
do_thing(_success)
# Easy enough, but what about args and kwargs?
#
# First - it's a sign that you're doing something "complicated" if it's
# hard to specify the types.
#
# But if we really had to, we can use Protocol:
class Aggregator(Protocol):
def __call__(self, *values: int, max_results: int | None = None) -> list[int]: ...
def process_numbers(data: Iterable[int], aggregator: Aggregator) -> list[int]: ...
def good_cb(*values: int, max_results: int | None = None) -> list[int]: ...
def bad_cb(*values: int, max_res: int | None) -> list[int]: ...
process_numbers([], good_cb) # OK
process_numbers(
[], bad_cb
) # Type error: incompatible type, due to keyword argument type and name mismatch