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:
- a parameter with a default gets both:
cups: int = 1(spaces around=when there's a hint) - a function that only prints and gives back nothing is labelled
-> None - a long hint you use again and again can get a name:
Basket = dict[str, int] - 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"))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))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
What does this print?
def brew(cups: int = 1) -> str: return f"{cups} cup(s) of tea" print(brew()) print(brew(3))Which return hint fits a function that only prints and gives nothing back?
- -> None
- -> str
What does this print?
Basket = dict[str, int] def total(basket: Basket) -> int: return sum(basket.values()) print(total({"tea": 20, "cake": 50}))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
What does this print?
def greet(name: str) -> None: print("Hi", name) result = greet("Mina") print(result)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
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 whensaltisTrue.Finish
apply_twice(rule: Callable[[int], int], x: int) -> int: it appliesruletox, then appliesruleagain to that answer.Using the alias
Basket = dict[str, int], writetotal(basket: Basket) -> int(the sum of the prices) andcheapest(basket: Basket) -> str | None(the name of the cheapest item, orNonefor an empty basket).