I have encountered the typing module's callable type in a Python book, and saw it tangentially referenced in a couple of videos, but I still don't really grasp what it is for, when to choose to use it, and how it works. (The O'Reilly text I am mostly using is more of a desktop reference than a textbook.)

Hoping someone here might have a suggestion for a good YouTube explanation/demonstration.

  • Jim@programming.dev
    ·
    1 year ago

    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