Skip to content

Instantly share code, notes, and snippets.

@Mulugruntz
Created October 23, 2023 08:27
Show Gist options
  • Save Mulugruntz/fe7a7c6cc9921c3c5f35dbbdd67df88e to your computer and use it in GitHub Desktop.
Save Mulugruntz/fe7a7c6cc9921c3c5f35dbbdd67df88e to your computer and use it in GitHub Desktop.
Example of Callback Protocol
$ python3.11 -m mypy main.py
main.py:19: error: Argument 2 to "add_something" has incompatible type "Callable[[str], int]"; expected "SomeCallback" [arg-type]
Found 1 error in 1 file (checked 1 source file)
from some_lib import add_something
def add_one(x: int) -> int:
return x + 1
def add_two(x: int) -> int:
return x + 2
def bad_signature(x: str) -> int:
return len(x)
def main() -> None:
print(add_something(1, add_one))
print(add_something(1, add_two))
print(add_something(1, bad_signature)) # IDEs and mypy will catch this!
if __name__ == '__main__':
main()
from typing import Protocol
class SomeCallback(Protocol):
def __call__(self, x: int) -> int:
...
def add_something(x: int, callback: SomeCallback) -> int:
return callback(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment