Command Palette

Search for a command to run...

Hectal
Phase 10: Type Hints and Modern Python
Python · Exercise 4 of 5 PreviousNext
Intermediate

A typed chat message

Define Role = Literal["user", "assistant", "system"] and a TypedDict called Message with role: Role and content: str.

Then write make_message(role, content) that returns a Message. If role is not one of the three allowed values, raise ValueError with the text bad role: <role>. Use typing.get_args(Role) to get the allowed roles instead of repeating them. The last line of the starter prints the message for "user" and "Hello".

What Check tests

  1. Message is a TypedDict with two required keys
  2. Message labels the role with Role
  3. make_message builds the dictionary
  4. A bad role raises ValueError with a clear text
  5. The program prints the user message

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.