Lesson 2 · Unit 03
Types and protocols
Hints the interpreter ignores and a checker reads
What you practise
- Type hints the interpreter ignores and a checker reads,
Optional, generics,Protocolas duck typing written down, abstract base classes
Try a question from this lesson
Pick one
The function says it takes an int. It is called with a string. What prints?
def double(n: int) -> int:
return n * 2
print(double("ab"))Hint
Who reads the annotations: the interpreter, or a separate tool?
Correct answer
abab
Why
The interpreter stores annotations and never checks them. The call runs, and "ab" * 2 is a perfectly good string. A type checker would have flagged this line without running anything.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Hints are metadata
Annotations are stored on the function and otherwise ignored when the code runs.
A type checker (mypy, pyright, your editor) reads them without running the program and reports calls that cannot be right. Hints are documentation that a tool can verify.
def double(n: int) -> int:
return n * 2
hints = double.__annotations__
print(list(hints)) # ['n', 'return']
print(double(2.5)) # 5.0, uncheckedConcept
A value that may be missing
int | None (older code writes Optional[int]) says: an int, or nothing.
A checker then makes you handle the nothing. Inside if age is not None: it treats age as a plain int. That is called narrowing, and it turns a crash in production into an error in your editor.
def find(users: dict[str, int],
name: str) -> int | None:
return users.get(name)
age = find({"ada": 36}, "ada")
if age is not None:
print(age + 1) # here age is int10 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.