Created
October 23, 2023 08:27
-
-
Save Mulugruntz/fe7a7c6cc9921c3c5f35dbbdd67df88e to your computer and use it in GitHub Desktop.
Example of Callback Protocol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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