this post was submitted on 21 Aug 2023
7 points (88.9% liked)

Learn Programming

1647 readers
1 users here now

Posting Etiquette

  1. Ask the main part of your question in the title. This should be concise but informative.

  2. Provide everything up front. Don't make people fish for more details in the comments. Provide background information and examples.

  3. Be present for follow up questions. Don't ask for help and run away. Stick around to answer questions and provide more details.

  4. Ask about the problem you're trying to solve. Don't focus too much on debugging your exact solution, as you may be going down the wrong path. Include as much information as you can about what you ultimately are trying to achieve. See more on this here: https://xyproblem.info/

Icon base by Delapouite under CC BY 3.0 with modifications to add a gradient

founded 1 year ago
MODERATORS
 

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.

you are viewing a single comment's thread
view the rest of the comments
[–] jim 9 points 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