Skip to content
Sarj Code Standards

prefer-named-literal-alias

Name multi-member Literal annotations with a reusable type alias.

Why

An inline multi-member Literal is an anonymous domain. Each copy drifts independently, and readers cannot tell which annotations share one closed set of values. The same drift can happen when separate aliases or an Enum describe the same domain.

Fix

Reuse the existing declaration when it expresses the same domain. Otherwise declare type Reason = Literal["a", "b"] once and annotate with Reason everywhere the domain is used.

Examples

Before — flagged A parameter repeats an anonymous Literal domain
app/errors.py
from typing import Literal
class FallbackError(RuntimeError):
def __init__(self, reason: Literal["unavailable", "failed"]) -> None:
super().__init__(reason)
self.reason: Literal["unavailable", "failed"] = reason
After — preferred Annotations share one named Literal alias
app/errors.py
from typing import Literal
type FallbackReason = Literal["unavailable", "failed"]
class FallbackError(RuntimeError):
def __init__(self, reason: FallbackReason) -> None:
super().__init__(reason)
self.reason: FallbackReason = reason