You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
description: Style and testing conventions for working with Python enums
4
+
compatibility: usethis, Python, pytest, enums
5
+
license: MIT
6
+
metadata:
7
+
version: "1.0"
8
+
---
9
+
10
+
# Working with Enums
11
+
12
+
## Exhaustiveness via `assert_never`
13
+
14
+
When handling all cases of an enum in `if`/`elif` chains, always include a final `else` branch that calls `assert_never` from `typing_extensions`. This ensures the type checker will flag any unhandled enum members if the enum is extended in the future.
15
+
16
+
```python
17
+
from typing_extensions import assert_never
18
+
19
+
from usethis._types.backend import BackendEnum
20
+
21
+
defhandle_backend(backend: BackendEnum) -> str:
22
+
if backend is BackendEnum.uv:
23
+
return"uv"
24
+
elif backend is BackendEnum.none:
25
+
return"none"
26
+
else:
27
+
assert_never(backend)
28
+
```
29
+
30
+
## Dicts with enum keys must have comprehensiveness tests
31
+
32
+
When a module-level dict uses an enum's members as its keys, add a unit test that asserts the dict's keys exactly match the set of all enum members. This prevents the dict from silently becoming incomplete when new members are added to the enum.
33
+
34
+
### Example test
35
+
36
+
```python
37
+
from usethis._core.status import_STATUS_TO_CLASSIFIER_MAP
38
+
from usethis._types.status import DevelopmentStatusEnum
Type checkers can catch missing cases in `if`/`elif` chains when `assert_never` is used, but they **cannot** catch missing keys in a dict literal. A dedicated unit test is the only reliable way to ensure that all enum members are represented.
0 commit comments