Skip to content

Pydantic lax-mode rewrites Pattern[str] to Pattern[LaxStr] and rejects re.Pattern[str] #2991

@oriori1703

Description

@oriori1703

Describe the Bug

Summary

When checking Pydantic models in Pyrefly, constructor parameters for re.Pattern[str] fields appear to be rewritten as Pattern[LaxStr] in lax mode.
This then causes valid re.Pattern[str] values (from re.compile(...)) to be rejected by static checking.

This seems inconsistent with runtime Pydantic behavior and likely indicates a bug/edge case in lax-type conversion for re.Pattern[...].

Minimal repro

import re
from typing import Literal
import pydantic

class RegexSignature(pydantic.BaseModel):
    type: Literal["regex"] = "regex"
    signature: re.Pattern[str]

_ = RegexSignature(type="regex", signature=re.compile(r"needle"))

Pyrefly output

ERROR Argument `Pattern[str]` is not assignable to parameter `signature` with type `Pattern[LaxStr]` in function `RegexSignature.__init__` [bad-argument-type]

(From my project this occurs in many callsites with the same shape.)

Expected behavior

No type error for re.compile(...) when field type is re.Pattern[str].

Actual behavior

Pyrefly reports Pattern[str] is not assignable to Pattern[LaxStr].

Why this looks wrong

  • Runtime Pydantic accepts both:
    • RegexSignature(signature=re.compile("x"))
    • RegexSignature(signature="x") (string pattern coercion)
  • Runtime Pydantic does not accept bytes for this field (e.g. signature=b"x" fails validation), so expanding to LaxStr may be over-broad for Pattern[str].
  • pyright and mypy report no errors on the same callsites.

Environment

  • pyrefly 0.59.0
  • pydantic 2.12.5
  • Python 3.14.3
  • Linux

Additional context

This appears related to Pyrefly’s Pydantic lax-mode conversion behavior:
https://pyrefly.org/en/docs/pydantic/#how-lax-mode-works-in-pyrefly

Potentially, re.Pattern[T] may need special handling instead of recursively applying str -> LaxStr inside the type parameter.

Important

Although I encountered and debugged the issue myself, I used AI to create the content of the issue. I then verified the content of the issue and checked that the reproduction is correct.

Sandbox Link

No response

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    pydanticIssues related to support for Pydanticv1-consider-addingTop-ranked but not in V1 milestone (consider adding)

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions