openedx-unsupported / wg-developer-experience

Old issue repository for the former Developer Experience Working Group
4 stars 0 forks source link

Use built-in generic types #130

Closed kdmccormick closed 1 year ago

kdmccormick commented 1 year ago

Context

Before Python 3.7, in order to fully annotate collections (lists, dicts, tuples), one had to import the type names from the typing module:

import typing as t

my_numbers: t.List[int] = [1, 2, 3, 4]
my_mapping: t.Dict[str, str] = {"key": "val"}
my_coordinates: t.Set[t.Tuple[int, int]]  = {(5, 6), (8, 10), (2, -2)}

Subscripting the built-in types directly (e.g., list[int]) would result in a syntax error like TypeError: 'type' object is not subscriptable. This is unfortunate because Tutor thoroughly annotates all types, including nested data structures, which are harder to read when using the type names from typing.

After Python 3.7, though, the built-in collection types can be used directly:

from __future__ import annotations  # <-- necessary until python 3.9

my_numbers: list[int] = [1, 2, 3, 4]
my_mapping: dict[str, str] = {"key": "val"}
my_coordinates: set[tuple[int, int]]  = {(5, 6), (8, 10), (2, -2)}

Tutor supports all non-end-of-life (EOL) Python versions. Since Python 3.6 is EOL, we can start using Python 3.7 features. Of course, we will need to retain Python 3.7 compatibility until Jun 2023 and Python 3.8 compatibility until Oct 2024, so the from __future__ import annotations line will need to stick around until then.

Acceptance Criteria

Throughout the entire Tutor codebase:

kdmccormick commented 1 year ago

@regisb does this look good to you?

Carlos-Muniz commented 1 year ago

tests/helpers.py has a function called run. It takes in an optional parameter and optionally returns using t.Optional[T]. In Python<=3.10, there is no substitute for t.Optional[T]. In 3.10+ we can change it to T|None , but we're not there yet