The first way to use it is with any type annotation: you just use it for documentation.
# int annotation
def add_1_to_number(x: int) -> int:
return x + 1
# callable annotation
def printer(x: int, func: Callable[[int], int]) -> None:
results = func(x)
print(f"Your results: {results}")
These type annotations can help document and make editors parse your code to make suggestions/auto-complete work better.
The second way to use it is by creating a callable. A callable is an abstract base class that requires you to implement the __call__
method. Your new callable can be called like any function.
class Greeter(Callable):
def __init__(self, greeting: str):
self.greeting = greeting
def __call__(self, name: str):
print(f"{self.greeting}, {name}")
say_hello = Greeter("Hello") # say_hello looks like a function
say_hello("jim") # Hello, jim