Divergence Patterns

What these actually are

Python’s type system is spread across dozens of PEPs, and mypy, pyrefly, ty, and zuban each implement those specs independently. Where a PEP is ambiguous or just silent on an edge case, the four checkers make different choices — so the same valid Python code gets accepted by one and rejected by another.

These aren’t bugs in the usual sense. They’re divergences — places where a reasonable reading of the spec leads to genuinely different behavior. Pytifex calls these divergence patterns: recurring categories of type-system edge cases that reliably cause disagreements.

Why this matters:

  • Library authors need code that passes every major checker, not just the one they happen to use.
  • Checker developers can use divergences to spot spec gaps and places where alignment would help.
  • Anyone studying type system soundness needs an actual taxonomy of where implementations diverge, instead of anecdotes.

The 10 built-in patterns

Defined as DivergencePattern instances in src/pytifex/patterns.py:

@dataclass
class DivergencePattern:
    id: str            # unique kebab-case id
    category: str      # grouping, e.g. "protocols", "generics"
    description: str   # what it tests
    pep_refs: list[str]  # relevant PEPs

protocol-defaults

Category PEP refs
protocols PEP 544

Protocol methods with default argument values. Checkers disagree on whether an implementing class has to use the same default or can pick its own.

typed-dict-total

Category PEP refs
typed-dict PEP 589, PEP 655

TypedDict mixing total=True/False inheritance with Required/NotRequired overrides. Combining a total=False base with a Required override in a subclass creates ambiguity about what’s actually mandatory at construction time.

typeguard-narrowing

Category PEP refs
type-narrowing PEP 647, PEP 742

TypeGuard/TypeIs functions with generic parameters, e.g. narrowing list[Animal] to list[Cat]. Checkers apply narrowing differently where container covariance is involved.

param-spec-decorator

Category PEP refs
callable PEP 612

A ParamSpec-based decorator stacked on @classmethod or @staticmethod. How cls/self gets captured through the decorator is where checkers disagree.

self-generic

Category PEP refs
generics PEP 673

Self as a return type inside a generic class with abstract methods. Tension between Self and the class’s own type parameters.

newtype-containers

Category PEP refs
newtypes PEP 484

NewType values inside generic containers, and whether the wrapper preserves the base type’s variance.

overload-literals

Category PEP refs
overloads PEP 484, PEP 586

Overloaded signatures with Literal types that partially overlap. Checkers differ on which overload wins and whether the overlap itself should be an error.

final-override

Category PEP refs
inheritance PEP 591

A Final attribute in a base class replaced by a @property in a subclass. Some checkers flag this as an override; others allow it since a property is technically a descriptor, not a reassignment.

keyword-vs-positional

Category PEP refs
callable PEP 544, PEP 570

A protocol method with keyword-only params, implemented with positional-or-keyword params instead. Checkers disagree on whether that satisfies the protocol.

bounded-typevars

Category PEP refs
generics PEP 484

A TypeVar bound to a generic type (e.g. T = TypeVar("T", bound=Comparable[Any])), used inside another generic. Complex enough constraint-solving that checkers land in different places.

How they actually get used

build_expert_prompt in prompts.py dumps every pattern description straight into the generation prompt:

def build_expert_prompt(num_examples: int = 10) -> str:
    patterns_text = "\n".join(
        f"- **{p.id}** ({p.category}): {p.description} [refs: {', '.join(p.pep_refs)}]"
        for p in PATTERNS
    )
    # patterns_text gets embedded in the generation prompt

This tells the model where to look instead of generating random type-annotated code and hoping. build_seed_based_prompt also throws in the first 6 patterns alongside the real GitHub seeds, as extra context.

Once a run starts: patterns go into the prompt → the LLM writes code targeting them → each snippet runs through all four checkers → only the ones where checkers disagree survive.

Examples that actually trigger disagreements

Protocol with a default value (protocol-defaults):

from typing import Protocol

class Drawable(Protocol):
    def draw(self, color: str = "black") -> None: ...

class Circle:
    def draw(self, color: str = "red") -> None:
        print(f"Drawing circle in {color}")

def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())  # does Circle satisfy Drawable? checkers disagree.

Some checkers require the default to match exactly; others only check the signature shape.

TypedDict with mixed Required/NotRequired (typed-dict-total):

from typing import TypedDict, Required, NotRequired

class Base(TypedDict, total=False):
    name: str
    age: int

class Strict(Base):
    name: Required[str]  # override: make name required
    email: NotRequired[str]

def greet(person: Strict) -> str:
    return f"Hello, {person['name']}"

greet({"name": "Alice"})  # is 'age' required or optional here?

Final attribute overridden by a property (final-override):

from typing import Final

class Config:
    max_retries: Final = 3

class CustomConfig(Config):
    @property
    def max_retries(self) -> int:  # overriding Final with a property
        return 5

Is a property an “override” of a Final attribute? Depends who you ask.

Adding a pattern

Append one to the PATTERNS list in src/pytifex/patterns.py:

PATTERNS = [
    # ... existing patterns ...
    DivergencePattern(
        id="my-new-pattern",
        category="some-category",
        description="Description of the type system edge case",
        pep_refs=["PEP 123"],
    ),
]

That’s it — build_expert_prompt picks it up automatically on the next run, no other changes needed.

Good places to look for new ones:

  • Closed issues on mypy, ty, or pyrefly where the fix itself was controversial.
  • PEP wording like “implementations may choose to…” or “this is left unspecified.”
  • Where two PEPs interact — ParamSpec + Protocol, TypedDict + Generic, that kind of thing.