Python 3D Academyবাংলা

Hinting functions: defaults, None, aliases and callbacks

🌍 In real life. A recipe card lists what goes in and what comes out: cups of rice: a number (usually 1), add salt: yes or no (usually no), and at the bottom makes: one pot of rice. You can cook from it without asking the person who wrote it.

A well-hinted function is that recipe card. Step by step:

  1. a parameter with a default gets both: cups: int = 1 (spaces around = when there's a hint)
  2. a function that only prints and gives back nothing is labelled -> None
  3. a long hint you use again and again can get a name: Basket = dict[str, int]
  4. a parameter that should be a function is labelled Callable[[int], int]: takes one int, gives back an int

The idea in one sentence: hint every parameter and the return value, including defaults (sugar: bool = False), None returns (-> None), type aliases and Callable for functions passed in.

Its words:

  • hinted default: cups: int = 1
  • -> None: the function returns nothing useful
  • type alias: Basket = dict[str, int], a name for a long hint
  • Callable[[int], int]: "a function that takes an int and returns an int"
def cook_rice(cups: int = 1, salt: bool = False) -> str:
    dish = f"{cups} cup(s) of rice"
    if salt:
        dish += " with salt"
    return dish

def announce(dish: str) -> None:
    print("Ready:", dish)

announce(cook_rice())
announce(cook_rice(3, True))
print(announce("tea"))
announce only prints, so it gives back None: that's why the last line prints "Ready: tea" and then None.

Two labels at once. With two parameters, the inspector checks each slot on its own. Here price_tag(item: str, rupees: int) is called once properly, and once with the price written as text, "50". Watch which light turns amber, and notice the answer still looks perfectly fine. That's the danger: a wrong type can slip through quietly.

Naming a hint, and hinting a function. A shop's basket is a dict of item to price, everywhere in the program. Writing dict[str, int] ten times is noisy, so give it a name once: Basket = dict[str, int]. That name is called a type alias.

From Chapter 27 you know functions can be passed around. Callable (from collections.abc) labels those parameters: Callable[[int], int] means "a function that takes one int and gives back an int". The first brackets list what goes in; the type after them is what comes out.

from collections.abc import Callable

Basket = dict[str, int]

def total(basket: Basket) -> int:
    return sum(basket.values())

def apply_discount(price: int, rule: Callable[[int], int]) -> int:
    return rule(price)

def eid_sale(price: int) -> int:
    return price - price // 10

basket: Basket = {"tea": 20, "cake": 50, "samosa": 15}
print(total(basket))
print(apply_discount(total(basket), eid_sale))
eid_sale takes an int and gives back an int, so it fits the label Callable[[int], int]. 85 minus a tenth (8) is 77.

Why hint whole functions? The signature becomes a contract: anyone can call the function correctly from its first line, and a type checker can catch a call like price_tag("pen", "50") before it quietly builds a wrong string.

Mistakes and edge cases.

  • A wrong type that "works". price_tag("pen", "50") runs without an error, but a price stored as text breaks the maths later (above).
  • -> None that returns something. If the hint says None, callers won't use the value; return it only if the hint says so.
  • A default that doesn't match its hint. count: int = "0" confuses every reader and tool.

Quiz

  1. What does this print?

    def brew(cups: int = 1) -> str:
        return f"{cups} cup(s) of tea"
    
    print(brew())
    print(brew(3))
  2. Which return hint fits a function that only prints and gives nothing back?

    • -> None
    • -> str
    • -> print
  3. What does this print?

    Basket = dict[str, int]
    
    def total(basket: Basket) -> int:
        return sum(basket.values())
    
    print(total({"tea": 20, "cake": 50}))
  4. What does Callable[[str], int] describe?

    • A function that takes one str and gives back an int
    • A list holding a str and an int
    • A function that takes an int and gives back a str
  5. What does this print?

    def greet(name: str) -> None:
        print("Hi", name)
    
    result = greet("Mina")
    print(result)
  6. The hints say price is an int, but this prints the wrong total, 5050. Which line passes the wrong type?

    def total(price: int, qty: int) -> int:
        return price * qty
    print(total("50", 2))

Coding tasks

  1. Write cook_rice(cups: int = 1, salt: bool = False) -> str. It gives back "1 cup of rice" for one cup and "3 cups of rice" for more, with " with salt" on the end when salt is True.

  2. Finish apply_twice(rule: Callable[[int], int], x: int) -> int: it applies rule to x, then applies rule again to that answer.

  3. Using the alias Basket = dict[str, int], write total(basket: Basket) -> int (the sum of the prices) and cheapest(basket: Basket) -> str | None (the name of the cheapest item, or None for an empty basket).