Bitpath

Lesson 2 · Unit 03

Types and protocols

Hints the interpreter ignores and a checker reads

13 exercisesabout 3 min

What you practise

  • Type hints the interpreter ignores and a checker reads, Optional, generics, Protocol as 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?

Python
def double(n: int) -> int:
    return n * 2

print(double("ab"))
Hint

Who reads the annotations: the interpreter, or a separate tool?

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.

Python
def double(n: int) -> int:
    return n * 2

hints = double.__annotations__
print(list(hints))     # ['n', 'return']
print(double(2.5))     # 5.0, unchecked

Concept

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.

Python
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 int

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy