Aliases¶
To simplify the writing of complex type annotations and encapsulate in a single location a type definition for easier later modification, a type alias can be defined.
Exercise (easy)
Create a type which can represent a grade (either an int or a float)
Correction
type Grade = int | float
Exercise (easy)
Create a type alias to represent the project assignment structure where a project number is mapped to a student number.
Correction
1type IdStudent = int
2type IdProject = int
3type Assignment = dict[IdProject, IdStudent]
4
5id_student: IdStudent = 1
6id_project: IdProject = 2
7assignment: Assignment = {id_project: id_student}
8
9assignment_: Assignment = {id_student: id_project} # strange
However in the last exercise, there is no distinction between an integer representing a student or a project. If you want to make explicitly the distinction, you can of course create a class (which is overkill here), or create a new type.
Exercise (easy)
Same exercise as before but distinguishing a student from a project. Complete the code in order to first create a valid assignment, and then make an error on purpose by switching roles.
1from typing import NewType
2
3IdStudentSafer = NewType("IdStudentSafer", int)
4IdProjectSafer = NewType("IdProjectSafer", int)
5type AssignmentSafer = dict[IdProjectSafer, IdStudentSafer]
6
7id_student_safer = IdStudentSafer(1)
8id_project_safer = IdProjectSafer(2)
9
10assignment_safer ...
11assignment_safer_ ...
Correction
1from typing import NewType
2
3IdStudentSafer = NewType("IdStudentSafer", int)
4IdProjectSafer = NewType("IdProjectSafer", int)
5type AssignmentSafer = dict[IdProjectSafer, IdStudentSafer]
6
7id_student_safer = IdStudentSafer(1)
8id_project_safer = IdProjectSafer(2)
9assignment_safer: AssignmentSafer = {id_project_safer: id_student_safer}
10assignment_safer_: AssignmentSafer = {id_student_safer: id_project_safer} # not ok
Conclusion¶
Type hints should be there to help, not a burden. Since they are optional, use them when you think they help the reader (which can be a colleague or even you in a few weeks / months). Type hints are relatively new in python and subject to evolution. You may encounter in the wild (on forums or even some LLMs) older syntax. The next feature will probably be the type intersection.