Skip to content

Python · correctness

prefer-str-enum

python:prefer-str-enum

Represent corroborated closed string domains with `StrEnum` or a named `Literal` alias.

Code
SARJ006
Default
error
Fix
none
Languages
python

Why

A named closed domain lets type checking and review catch invalid values and incomplete handling.

Fix

Define a `StrEnum` for model fields, or reuse one named `Literal` alias across transparent builders.

Before / after

Executed by this rule’s unit tests.

Before

String field backed by a closed choice collection

app/order.py · focus
class Order:
    statuses = ("pending", "shipped")
    status: str = "pending"

After

Closed domain represented by a string enum

app/order.py · focus
from enum import StrEnum

class Status(StrEnum):
    PENDING = "pending"
    SHIPPED = "shipped"

class Order:
    status: Status = Status.PENDING

Limits

  • The rule requires corroborating choice collections, comparison clusters, or repeated literal domains.
  • Tests, generated code, external vocabularies, and open-ended name domains receive conservative exemptions.