.. `type alias first `_ `type alias second `_ `new type `_ .. _`sec:alias`: 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. .. admonition:: Exercise (easy) Create a type which can represent a grade (either an int or a float) .. _`ex:type_alias`: .. collapse:: Correction .. code-block:: python type Grade = int | float .. admonition:: Exercise (easy) Create a type alias to represent the project assignment structure where a project number is mapped to a student number. .. _`ex:type_alias_2`: .. collapse:: Correction .. code-block:: python :linenos: type IdStudent = int type IdProject = int type Assignment = dict[IdProject, IdStudent] id_student: IdStudent = 1 id_project: IdProject = 2 assignment: Assignment = {id_project: id_student} assignment_: 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 `_. .. admonition:: 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. .. code-block:: python :linenos: from typing import NewType IdStudentSafer = NewType("IdStudentSafer", int) IdProjectSafer = NewType("IdProjectSafer", int) type AssignmentSafer = dict[IdProjectSafer, IdStudentSafer] id_student_safer = IdStudentSafer(1) id_project_safer = IdProjectSafer(2) assignment_safer ... assignment_safer_ ... .. _`ex:new_type`: .. collapse:: Correction .. code-block:: python :linenos: from typing import NewType IdStudentSafer = NewType("IdStudentSafer", int) IdProjectSafer = NewType("IdProjectSafer", int) type AssignmentSafer = dict[IdProjectSafer, IdStudentSafer] id_student_safer = IdStudentSafer(1) id_project_safer = IdProjectSafer(2) assignment_safer: AssignmentSafer = {id_project_safer: id_student_safer} assignment_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.