{"course":{"slug":"python-for-ai","title":"Python, from Zero, for AI","url":"https://addaly.com/learn/python-for-ai","level":"beginner","track":"build"},"lesson":{"slug":"docstrings-and-type-hints","title":"Saying what a function expects, and what checks it","url":"https://addaly.com/learn/python-for-ai/docstrings-and-type-hints","position":25,"of":89,"minutes":8,"answer":"Type hints are metadata that Python never enforces, so their value comes from a checker like mypy, from editor support, and from documenting units and edge cases the code cannot show.","keyIdea":"Type hints are metadata that Python never enforces, so their value comes from a checker like mypy, from editor support, and from documenting units and edge cases the code cannot show."},"body":{"format":"markdown","text":"## The docstring is the first line of the body\n\n```python\ndef split_bill(total, people, tip_percent=0):\n    \"\"\"Return each person's share, rounded to 2 decimals.\n\n    total: the bill before tip, in rupees\n    people: how many are paying; must be at least 1\n    tip_percent: 10 means 10 percent\n\n    Raises ValueError if people is less than 1.\n    \"\"\"\n```\n\nA string as the first statement of a function, module or class becomes its documentation. It is not a comment: it is stored on the object, so `help(split_bill)` prints it, editors show it on hover, and `python -m pydoc yourmodule` turns a file into readable documentation with no extra tooling.\n\nWrite the first line as a sentence saying what the function **returns**, in the imperative. Then the arguments in terms a caller needs: units, ranges, what \"must\" means. Then what it raises. Three-quarters of the value is in the units: `total` in rupees or paise is exactly the sort of thing that gets guessed wrong.\n\nDo not restate the code. `\"\"\"Adds a and b.\"\"\"` above `def add(a, b)` is noise. Document the parts a reader cannot see: units, edge cases, side effects, and why the odd-looking line is there.\n\n## Type hints\n\n```python\ndef split_bill(total: float, people: int, tip_percent: float = 0) -> float:\n    ...\n```\n\nThe annotations after each colon and after the arrow say what types are expected. Common forms:\n\n```python\nfrom typing import Any\n\nnames: list[str]\nscores: dict[str, int]\nmaybe: str | None            # 3.10+; earlier, Optional[str]\npairs: tuple[int, int]\nanything: Any\n```\n\nBefore Python 3.9 you needed `from typing import List, Dict`. In modern code, use the lowercase built-ins.\n\n## Here is the honest part: nothing enforces them\n\n```python\nsplit_bill(\"lots\", \"several\")     # runs happily until the arithmetic fails\n```\n\nPython does not check annotations at runtime. They are metadata. A function annotated `-> int` can return a string and nothing complains. Anyone who tells you type hints make Python type-safe is overselling them.\n\nWhat they actually buy you:\n\n- **A checker you run yourself.** `mypy` and `pyright` are free, read the annotations and report mismatches before you run anything. `pip install mypy && mypy yourfile.py` takes a minute to set up and catches the class of bug where a function returns `None` on one path and a number on another.\n- **Editor help.** Autocomplete and inline errors get dramatically better, because the editor knows what `people` is.\n- **Better AI assistance.** An assistant reading annotated code guesses far less. This is a small, real, measurable benefit.\n- **Documentation that cannot drift as easily** as a prose comment, because the checker complains when it stops matching.\n\nThe costs are real too. Hints on heavily dynamic code get long and ugly, and a codebase with hints on 40 per cent of its functions gives a false sense of coverage. The usual advice, and it is good advice: annotate the boundaries (the functions other modules call, and anything handling external data) and leave short internal helpers bare.\n\n## Runtime validation is a separate job\n\nIf you need the check to actually happen, do it:\n\n```python\nif people < 1:\n    raise ValueError(f\"people must be at least 1, got {people}\")\n```\n\nOr use `pydantic`, a free library that builds validation from annotations and is the standard way to parse and check JSON from an API. It is a different thing from `mypy`: `mypy` checks your code before it runs; `pydantic` checks your data while it runs. You often want both, for different reasons.\n\n## Comments earn their place differently\n\n```python\n# The API returns paise for historical reasons; convert once, here.\namount = raw / 100\n```\n\nGood comments explain **why**. The code already says what. A comment that repeats the line beneath it will eventually contradict it, because someone will change the line and not the comment, and then it is worse than nothing.\n\nThe one comment style always worth writing is the one recording a decision that looks wrong: the sleep that exists because the vendor rate-limits, the extra retry, the strange ordering. Without it, someone deletes the line and the bug returns in six months.\n\n## Try this now\n\nTake the longest function you have written so far. Add a docstring giving units for every argument, annotate the signature, then run `pip install mypy` and `mypy yourfile.py`. Fix whatever it reports. The first run on real code usually finds something genuine."},"check":{"question":"A team adds `-> float` to every function and reports that the annotations are working because the code stopped crashing on bad input. What has most likely happened?","options":[{"text":"Annotations coerce values to the declared type at return time, which quietly converted the bad inputs.","correct":false,"tempting":"Attributes coercion to annotations; Python performs none, so nothing about the values changed."},{"text":"Something else changed at the same time; annotations are not checked at runtime and cannot stop a crash on their own.","correct":true},{"text":"Annotations enable Python's optional strict mode, which validates arguments once a module is fully annotated.","correct":false,"tempting":"Invents a strict mode; there is no runtime flag that turns annotations into checks."},{"text":"The functions now raise TypeError earlier, so the eventual crash is simply happening in a different place.","correct":false,"tempting":"Assumes an earlier failure that never occurs, since the interpreter ignores the annotation entirely when calling."}]},"prev":{"slug":"returning-values","title":"Returning: one value, several values, or nothing at all","url":"https://addaly.com/learn/python-for-ai/returning-values"},"next":{"slug":"modules-and-imports","title":"Modules: splitting a script across files without breaking it","url":"https://addaly.com/learn/python-for-ai/modules-and-imports"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Saying what a function expects, and what checks it', in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/docstrings-and-type-hints (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Saying what a function expects, and what checks it","courseTitle":"Python, from Zero, for AI","module":{"index":3,"slug":"functions-and-structure","title":"Functions, modules, and code you can read again in March"},"answer":null,"keyIdea":"Type hints are metadata that Python never enforces, so their value comes from a checker like mypy, from editor support, and from documenting units and edge cases the code cannot show.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-docstring-is-the-first-line-of-the-body","runs":[{"text":"The docstring is the first line of the body"}]},{"t":"code","lang":"python","label":"Python","text":"def split_bill(total, people, tip_percent=0):\n    \"\"\"Return each person's share, rounded to 2 decimals.\n\n    total: the bill before tip, in rupees\n    people: how many are paying; must be at least 1\n    tip_percent: 10 means 10 percent\n\n    Raises ValueError if people is less than 1.\n    \"\"\""},{"t":"p","runs":[{"text":"A string as the first statement of a function, module or class becomes its documentation. It is not a comment: it is stored on the object, so "},{"text":"help(split_bill)","code":true},{"text":" prints it, editors show it on hover, and "},{"text":"python -m pydoc yourmodule","code":true},{"text":" turns a file into readable documentation with no extra tooling."}]},{"t":"p","runs":[{"text":"Write the first line as a sentence saying what the function "},{"text":"returns","b":true},{"text":", in the imperative. Then the arguments in terms a caller needs: units, ranges, what “must” means. Then what it raises. Three-quarters of the value is in the units: "},{"text":"total","code":true},{"text":" in rupees or paise is exactly the sort of thing that gets guessed wrong."}]},{"t":"p","runs":[{"text":"Do not restate the code. "},{"text":"\"\"\"Adds a and b.\"\"\"","code":true},{"text":" above "},{"text":"def add(a, b)","code":true},{"text":" is noise. Document the parts a reader cannot see: units, edge cases, side effects, and why the odd-looking line is there."}]},{"t":"h2","id":"type-hints","runs":[{"text":"Type hints"}]},{"t":"code","lang":"python","label":"Python","text":"def split_bill(total: float, people: int, tip_percent: float = 0) -> float:\n    ..."},{"t":"p","runs":[{"text":"The annotations after each colon and after the arrow say what types are expected. Common forms:"}]},{"t":"code","lang":"python","label":"Python","text":"from typing import Any\n\nnames: list[str]\nscores: dict[str, int]\nmaybe: str | None            # 3.10+; earlier, Optional[str]\npairs: tuple[int, int]\nanything: Any"},{"t":"p","runs":[{"text":"Before Python 3.9 you needed "},{"text":"from typing import List, Dict","code":true},{"text":". In modern code, use the lowercase built-ins."}]},{"t":"h2","id":"here-is-the-honest-part-nothing-enforces-them","runs":[{"text":"Here is the honest part: nothing enforces them"}]},{"t":"code","lang":"python","label":"Python","text":"split_bill(\"lots\", \"several\")     # runs happily until the arithmetic fails"},{"t":"p","runs":[{"text":"Python does not check annotations at runtime. They are metadata. A function annotated "},{"text":"-> int","code":true},{"text":" can return a string and nothing complains. Anyone who tells you type hints make Python type-safe is overselling them."}]},{"t":"p","runs":[{"text":"What they actually buy you:"}]},{"t":"ul","items":[[{"text":"A checker you run yourself.","b":true},{"text":" "},{"text":"mypy","code":true},{"text":" and "},{"text":"pyright","code":true},{"text":" are free, read the annotations and report mismatches before you run anything. "},{"text":"pip install mypy && mypy yourfile.py","code":true},{"text":" takes a minute to set up and catches the class of bug where a function returns "},{"text":"None","code":true},{"text":" on one path and a number on another."}],[{"text":"Editor help.","b":true},{"text":" Autocomplete and inline errors get dramatically better, because the editor knows what "},{"text":"people","code":true},{"text":" is."}],[{"text":"Better AI assistance.","b":true},{"text":" An assistant reading annotated code guesses far less. This is a small, real, measurable benefit."}],[{"text":"Documentation that cannot drift as easily","b":true},{"text":" as a prose comment, because the checker complains when it stops matching."}]]},{"t":"p","runs":[{"text":"The costs are real too. Hints on heavily dynamic code get long and ugly, and a codebase with hints on 40 per cent of its functions gives a false sense of coverage. The usual advice, and it is good advice: annotate the boundaries (the functions other modules call, and anything handling external data) and leave short internal helpers bare."}]},{"t":"h2","id":"runtime-validation-is-a-separate-job","runs":[{"text":"Runtime validation is a separate job"}]},{"t":"p","runs":[{"text":"If you need the check to actually happen, do it:"}]},{"t":"code","lang":"python","label":"Python","text":"if people < 1:\n    raise ValueError(f\"people must be at least 1, got {people}\")"},{"t":"p","runs":[{"text":"Or use "},{"text":"pydantic","code":true},{"text":", a free library that builds validation from annotations and is the standard way to parse and check JSON from an API. It is a different thing from "},{"text":"mypy","code":true},{"text":": "},{"text":"mypy","code":true},{"text":" checks your code before it runs; "},{"text":"pydantic","code":true},{"text":" checks your data while it runs. You often want both, for different reasons."}]},{"t":"h2","id":"comments-earn-their-place-differently","runs":[{"text":"Comments earn their place differently"}]},{"t":"code","lang":"python","label":"Python","text":"# The API returns paise for historical reasons; convert once, here.\namount = raw / 100"},{"t":"p","runs":[{"text":"Good comments explain "},{"text":"why","b":true},{"text":". The code already says what. A comment that repeats the line beneath it will eventually contradict it, because someone will change the line and not the comment, and then it is worse than nothing."}]},{"t":"p","runs":[{"text":"The one comment style always worth writing is the one recording a decision that looks wrong: the sleep that exists because the vendor rate-limits, the extra retry, the strange ordering. Without it, someone deletes the line and the bug returns in six months."}]},{"t":"h2","id":"try-this-now","runs":[{"text":"Try this now"}],"role":"try"},{"t":"p","runs":[{"text":"Take the longest function you have written so far. Add a docstring giving units for every argument, annotate the signature, then run "},{"text":"pip install mypy","code":true},{"text":" and "},{"text":"mypy yourfile.py","code":true},{"text":". Fix whatever it reports. The first run on real code usually finds something genuine."}]}],"check":{"question":[{"text":"A team adds "},{"text":"-> float","code":true},{"text":" to every function and reports that the annotations are working because the code stopped crashing on bad input. What has most likely happened?"}],"options":[{"text":[{"text":"Annotations coerce values to the declared type at return time, which quietly converted the bad inputs."}],"correct":false,"tempting":[{"text":"Attributes coercion to annotations; Python performs none, so nothing about the values changed."}]},{"text":[{"text":"Something else changed at the same time; annotations are not checked at runtime and cannot stop a crash on their own."}],"correct":true,"tempting":null},{"text":[{"text":"Annotations enable Python’s optional strict mode, which validates arguments once a module is fully annotated."}],"correct":false,"tempting":[{"text":"Invents a strict mode; there is no runtime flag that turns annotations into checks."}]},{"text":[{"text":"The functions now raise TypeError earlier, so the eventual crash is simply happening in a different place."}],"correct":false,"tempting":[{"text":"Assumes an earlier failure that never occurs, since the interpreter ignores the annotation entirely when calling."}]}],"order":[3,0,1,2],"why":null},"prev":{"slug":"returning-values","title":"Returning: one value, several values, or nothing at all","minutes":7},"next":{"slug":"modules-and-imports","title":"Modules: splitting a script across files without breaking it","minutes":8}}}