Type hints record the types a Python function expects and returns. They make a function’s contract easier to read and maintain, especially when other developers need to use it. Python does not enforce these hints at runtime; static type checkers can inspect them separately. section 2.7.2
Consider a balance-formatting function. An input annotation of `str` describes the value received from `input()`. Its return annotation changes from `None` when the function prints directly to `str` when it returns a formatted balance. Returning the string lets the caller decide whether to print it, write it to a file, or use it in an API response. section 1.5.2
Listing 1.4 Returning a string
def print_balance(current_balance: str) -> str: #1
"""
Returns the current balance in a formatted string.
Parameters:
- current_balance (str): The current balance to be formatted, as a string.
Returns: #2
- str: The formatted current balance. #2
"""
return f"Current Balance: ${float(current_balance):,.2f}" #3
# Ask the user to enter the current balance
user_input = input("Enter current balance: ") #4
# Call the function to get the formatted balance and then print it
formatted_balance = print_balance(user_input) #5
print(formatted_balance) #6
The `-> str` annotation matches the returned formatted string; the caller handles printing. section 1.5.2
Hints also help when a dictionary selects a payment-record parser. Without a declared type, the dictionary does not clearly show whether its values are functions, what arguments they accept, or what they return. section 2.7.1 section 2.7.2
parser_functions: Dict[str, Callable[[str], Dict[str, str]]] = {
`Dict[str, Callable[[str], Dict[str, str]]]` describes a dictionary keyed by record-type strings whose functions take one string and return a string-to-string dictionary. section 2.7.2
Treat hints as documentation and a starting point for static checking, not as input validation. Tools such as mypy, Pyright, and Pyre can check annotated code. section 2.7.2
















