4 Types, then a docstring
Read the tutorial. Build it yourself is the other way to read this part.
just setupTo learn what count takes and what it gives, a reader must now read its body. Its signature can say it at a
glance, and an editor can check it. One line under the signature can say what the function does. Neither changes
what count does, so the tests pass as before.
The code before this part. The code after it.
4.1 Types
The signature def count(text): does not say what text is, or what count gives back. Types say it. count
takes a str, and gives a dict[str, int], a dictionary from words to counts. The body stays the same.
A patch to src/tally/__init__.py.
In src/tally/__init__.py, the signature of count now says text: str, and -> dict[str, int] for what it
gives back. The body is the same.
uv run python -m unittest discover -s tests -qThe three tests pass as before, because types change what the code says, not what it does.
What changed
src/tally/__init__.py: the signature says what goes in and what comes out. 1 line added, 1 removed. The file.- look at
def count(text: str) -> dict[str, int]:
- look at
The diff of src/tally/__init__.py
@@ -3,7 +3,7 @@
import sys
-def count(text):
+def count(text: str) -> dict[str, int]:
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 14.2 A docstring
The types say what count takes and gives, but not what it does with the text. A docstring says it. It is a string on
the first line of a function. Python keeps it in count.__doc__, and help(count) prints it.
A patch to src/tally/__init__.py.
In src/tally/__init__.py, the first line of count is now its docstring. It says that count ignores case.
uv run python -c "import tally; print(tally.count.__doc__)"It prints the docstring, How many times each word of `text` appears, ignoring case.
What changed
src/tally/__init__.py: one line under the signature says what the function does. 1 line added. The file.- look at
"How many times each word of `text` appears, ignoring case."
- look at
The diff of src/tally/__init__.py
@@ -4,6 +4,7 @@ import sys
def count(text: str) -> dict[str, int]:
+ "How many times each word of `text` appears, ignoring case."
counts = {}
for word in text.lower().split():
counts[word] = counts.get(word, 0) + 1