Python Tutorial / Describe Function Inputs and Results with Type Hints

Type hints describe expected input and result types for readers and static-analysis tools. Ordinary Python execution does not enforce them automatically, so distinguish annotations from runtime validation.

Read the contract without assuming conversion

amount: int says that an integer is expected; it does not convert a value to int. The annotation -> str describes an expected string result. Editors and static checkers can use this information to find unsuitable calls, while external input still needs validation.

list[int] describes a list of integers, and str | None allows either a string or absence. Examples target Python 3.12 or later. Code that dynamically inspects annotations should check the relevant version’s evaluation rules.

For the relevant APIs and platform requirements, see Describe Function Inputs and Results with Type Hints documentation.

Compare hints with explicit checks

Save the complete code below as hints.py in a separate practice folder, using UTF-8. Run python hints.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

def format_amount(amount: int) -> str:
    if type(amount) is not int or amount < 0:
        raise ValueError("invalid amount")
    return f"{amount:,} KRW"

def find_name(names: dict[str, str], key: str) -> str | None:
    return names.get(key)

print(format_amount(8000))
print(find_name({"e1": "lunch"}, "missing"))
try:
    format_amount("8000")
except ValueError:
    print("rejected")

Expected output:

8,000 KRW
None
rejected

Run an optional static checker

For example, install mypy in the project environment and check the file:

python -m pip install mypy
python -m mypy hints.py

The intentional string argument can be reported as a static error. Correct the call or add deliberate input conversion rather than making every value Any merely to silence diagnostics.

Static checking does not guarantee file availability, a working network or valid business data. The rejected runtime output comes from the manual validation code, not from automatic enforcement of the annotation.

Handle values that may be absent

find_name may return None. Check for that case before calling string methods, and make the annotation agree with every actual return path. A caller should not have to guess whether absence is possible.

Whether an external JSON string "8000" should be parsed or rejected is an input policy beyond its annotation. Test both expected result types and validation paths. The automated testing lesson provides repeatable checks for those behaviors.