Predict the output
What do the two lines print?
from typing import Protocol
class Users(Protocol):
def get_email(self, user_id: int) -> str | None: ...
class FakeUsers:
def __init__(self, data: dict[int, str]) -> None:
self.data = data
def get_email(self, user_id: int) -> str | None:
return self.data.get(user_id)
def greeting(users: Users, user_id: int) -> str:
email = users.get_email(user_id)
return f"Hi {email}" if email else "Hi guest"
fake = FakeUsers({1: "ana@example.com"})
print(greeting(fake, 1))
print(greeting(fake, 2))Hint 1 of 1
What does dict.get return for a missing key?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Hi ana@example.com then Hi guest
Correct. The fake knows user 1 and returns None for 2.
A fake is a small working implementation, here a dict behind the same method. It returns data for user 1 and None for user 2, so the test checks real behaviour, not which calls were made.
Why not the others?
- B
Hi ana@example.comtwice. User 2 isn't in the fake's data. - C A type error. FakeUsers matches the Users protocol structurally.
- D
Hi NonethenHi guest. User 1 exists.