Command Palette

Search for a command to run...

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

A validator that reads type hints

Write validate(cls, data) that checks a dictionary against the type hints of a class and returns a list of problem strings (an empty list means the data is valid). Use typing.get_type_hints(cls) to get the fields (Topic 10.7).

Go through the fields in the order the class declares them. If a field is missing from data and the class gives it no default value, add the text "<name>: missing". If a value has the wrong type, add "<name>: expected <type>, got <type>" using the class names, for example "age: expected int, got str".

A field that has a default on the class may be left out of data. Only plain classes such as int, str and bool need to work.

What Check tests

  1. Valid data gives an empty list
  2. A wrong type is reported
  3. A missing field without a default is reported
  4. A field with a default may be left out, and a wrong default-field type is reported
  5. Problems come in field order
  6. An empty dictionary reports every field without a default, and extra keys are ignored
  7. It works for another class too

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.