Skip to content

Keep a regex holding a quote unchanged in the pattern literal - #6790

Merged
Koudai Aono (koxudaxi) merged 2 commits into
merge-inherited-enum-classes-v2from
regex-quote-literal-5355
Nov 13, 2026
Merged

Koudai Aono (koxudaxi) merged 2 commits into
merge-inherited-enum-classes-v2from
regex-quote-literal-5355

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Fixes: #6789

Summary by CodeRabbit

  • Bug Fixes
    • Generated Pydantic v2 constraints now preserve regex patterns containing quotes, including escaped apostrophes, without changing the pattern’s meaning.

@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Pydantic v2 regex rendering now selects a raw-string delimiter that is absent from the pattern, or falls back to a regular string when needed. Generated-output expectations and regression coverage are updated for patterns containing quotes.

Changes: Pydantic v2 regex pattern literals

Layer / File(s) Summary
Raw literal generation and regex rendering
src/datamodel_code_generator/_python_syntax.py, src/datamodel_code_generator/model/pydantic_v2/types.py
The syntax helper supports raw literals with single or double quotes. Pydantic v2 regex rendering uses the helper and falls back to a regular string when control-character escaping would change the regex or the pattern cannot be represented as a raw literal.
Generated output and regression coverage
tests/data/expected/main/jsonschema/*, tests/data/expected/main/openapi/pattern/pydantic_v2.py, tests/main/jsonschema/test_main_jsonschema.py, tests/main/jsonschema/test_main_jsonschema.refs, tests/main/test_payload_validation.refs, scripts/behaviour_diff_allowlist.toml
Generated pattern literal spellings are updated, and the JSON Schema property-name pattern test and payload-validation references are added. The allowlist records the escaped-quote pattern difference.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related PRs

Merge Risk: Low · previous review 19b9d

This change keeps quoted regex patterns unchanged in generated Pydantic output, and no code defect was found. The Behaviour diff gate reported a violation for the new quoted-pattern fixture even though the new allowlist entry appears to cover it. Confirm that the gate passes on the latest commit before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title states that a regex containing a quote is kept unchanged in the pattern literal. The raw summary confirms this is the main change: _get_regex_literal now renders patterns with `raw_literal…
Linked Issues check Passed Objective [#6789]: a JSON Schema pattern containing a single quote must be emitted unchanged in the generated pattern literal. Evidence from the PR summary: _python_syntax.py replaces `raw_single_qu…
Out of Scope Changes check Passed All changed files relate to the #6789 pattern-literal fix. The source changes are in _python_syntax.py and model/pydantic_v2/types.py. The expected snapshots and test files cover the new rendering…
Full details: Title check

Explanation

The title states that a regex containing a quote is kept unchanged in the pattern literal. The raw summary confirms this is the main change: _get_regex_literal now renders patterns with raw_literal, which picks a usable quote, so the pattern is no longer escaped. The linked issue #6789 asks for the same behaviour. The title is specific and accurate, so it passes.

Full details: Linked Issues check

Explanation

Objective [#6789]: a JSON Schema pattern containing a single quote must be emitted unchanged in the generated pattern literal. Evidence from the PR summary: _python_syntax.py replaces raw_single_quoted with raw_literal, which selects the first quote character absent from the escaped text. types.py _get_regex_literal uses raw_literal. For ^[a-z'*]+$, the single quote is no longer escaped, so the output is a raw literal with the pattern unchanged, not r'^[a-z\'*]+$'. Snapshot updates (regex_literal_text, pattern_escaped_quote.py, pattern.py) show the same regex value in the new literal forms. jsonschema_property_names_pattern_quotes.py and its test cover single, double, and mixed quote keys. The fixture tests/data/jsonschema/property_names_pattern_quotes.json is in ignored_files, so the test input was not inspected. The expected output is reviewable and supports the behavior. The stack members (#6775, #6776, #6777, #6781) are not needed for this objective. Their stated changes concern enum merging and do not touch pattern literal rendering. Stack roll-up: the objective is Addressed by the current PR (#6790) alone. Residual uncertainty: the excluded fixture input cannot be checked directly, and the PR reports no test run results.

Full details: Out of Scope Changes check

Explanation

All changed files relate to the #6789 pattern-literal fix. The source changes are in _python_syntax.py and model/pydantic_v2/types.py. The expected snapshots and test files cover the new rendering and its regression test. scripts/behaviour_diff_allowlist.toml adds an accepted default-output change for patterns with an escaped single quote, citing owner decision #6789. This entry records the rendering change for the behaviour-diff check, so it is connected to the objective. It is a suppression entry, so reviewers should confirm it does not hide unrelated regressions. The .refs manifest updates register the new test and fixture. No unrelated behavior change was identified in the summary. Excluded paths were not inspected.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 86c0be0 and 19b9df5.

Files ignored due to path filters: 1

  • tests/data/jsonschema/property_names_pattern_quotes.json is excluded by !tests/data/**/*.json and included by none
Files selected for processing: 12

  • scripts/behaviour_diff_allowlist.toml
  • src/datamodel_code_generator/_python_syntax.py
  • src/datamodel_code_generator/model/pydantic_v2/types.py
  • tests/data/expected/main/jsonschema/jsonschema_property_names_pattern_quotes.py
  • tests/data/expected/main/jsonschema/pattern.py
  • tests/data/expected/main/jsonschema/pattern_escaped_quote.py
  • tests/data/expected/main/jsonschema/string_literal_text/regex_literal_text[pydantic_v2.BaseModel].py
  • tests/data/expected/main/jsonschema/string_literal_text/regex_literal_text[pydantic_v2.dataclass].py
  • tests/data/expected/main/openapi/pattern/pydantic_v2.py
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/main/jsonschema/test_main_jsonschema.refs
  • tests/main/test_payload_validation.refs

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@koxudaxi
Koudai Aono (koxudaxi) marked this pull request as ready for review November 13, 2026 03:04
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T03:05:56.371934Z 19b9df5 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions

Copy link
Copy Markdown
Contributor

@codecov

codecov Bot commented Nov 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 48.93%

2 warnings

⚠️ Walltime results may be unreliable

Some benchmarks used the Walltime instrument outside CodSpeed Macro Runners, which can make the results inconsistent.

Learn more about Macro Runners

See affected benchmarks

⚠️ 53 benchmarks with a significant change ran on different hardware

Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚡ 53 improved benchmarks
⏩ 98 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_perf_simple_msgspec_unset_field_rendering 591.1 ms 333.3 ms +77.35%
⚡ test_perf_client_calls[sync] 44.5 ms 25.6 ms +73.87%
⚡ test_perf_client_calls[async] 48.1 ms 28.6 ms +67.8%
⚡ test_perf_load_pyproject_config[config-multiple] 260.7 µs 155.6 µs +67.55%
⚡ test_perf_load_pyproject_config[config-None] 239 µs 143.6 µs +66.49%
⚡ test_perf_load_pyproject_config[mapping-None] 242.2 µs 145.7 µs +66.21%
⚡ test_perf_load_pyproject_config[mapping-multiple] 257.8 µs 155.5 µs +65.76%
⚡ test_perf_scalar_root_collapsed_builtin 239.6 ms 145.6 ms +64.48%
⚡ test_perf_large_models_typed_dict[total-false-requiredness] 1,413.2 ms 901.5 ms +56.76%
⚡ test_perf_ordinary_array_constraint_generation 2.4 s 1.6 s +56.49%
⚡ test_perf_large_models_msgspec 2.4 s 1.5 s +55.71%
⚡ test_perf_large_models_dataclass_builtin 1.6 s 1.1 s +54.27%
⚡ test_perf_local_reference_file_resolution 159.1 ms 103.2 ms +54.21%
⚡ test_perf_large_models_typed_dict[legacy-requiredness] 1,402.3 ms 911.1 ms +53.91%
⚡ test_perf_large_models_single_module_stdout 1.9 s 1.3 s +53.37%
⚡ test_perf_duplicate_names 1,196.8 ms 783.7 ms +52.71%
⚡ test_perf_openapi_large 3.8 s 2.5 s +51.9%
⚡ test_perf_large_models_pydantic_v2 4.1 s 2.7 s +51.72%
⚡ test_perf_large_models_pydantic_v2_builtin_double_quotes 1.7 s 1.1 s +51.39%
⚡ test_perf_mapped_reference_users 983.3 ms 649.9 ms +51.29%
... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing regex-quote-literal-5355 (fd3b52a) with merge-inherited-enum-classes-v2 (86c0be0)

Open in CodSpeed

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@koxudaxi
Koudai Aono (koxudaxi) merged commit 30b8128 into main Nov 13, 2026
118 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the regex-quote-literal-5355 branch November 13, 2026 05:05
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: Breaking changes detected

Reasoning: The PR changes how the Pydantic v2 type manager writes regex pattern literals. raw_single_quoted becomes raw_literal: it picks a quote the pattern does not contain and no longer backslash-escapes a single quote, and it falls back to a plain literal when the pattern holds both quotes. The behaviour diff gate marks the pattern.json, openapi pattern.yaml, regex_literal_text.json and property_names_pattern_quotes.json cells as accepted constraint changes under default options, so this changes default generated output. Validation stays the same under Python re, but the stored pattern string and the pattern that model_json_schema publishes now lose the extra backslash, and the source text of the generated fields changes, so it is reported as a code generation change. The removed and renamed helpers in the private _python_syntax module, and the narrowed value of the module-level escape_characters in model.pydantic_v2.types, are internal implementation details and not reported separately. The large edit to behaviour_diff_allowlist.toml is workflow configuration, and the docs and test changes only reflect the new output. There are no CLI option, template, Python version or error handling changes.

Content for Release Notes

Code Generation Changes

  • Regex patterns containing quotes are written differently in Pydantic v2 output - With pydantic_v2.BaseModel and pydantic_v2.dataclass output, a pattern containing a single quote used to be written as a single-quoted raw literal with the quote escaped by a backslash, for example constr(pattern=r'^it\'s$'). Because raw literals keep backslashes, the runtime pattern string had an extra backslash before the quote. The generator now picks a quote character the pattern does not use, so this becomes constr(pattern=r"^it's$"). A pattern containing both quote characters is now written as a plain (non-raw) literal, for example '^a-z\'"+$' instead of r'^a-z\'"+$', and backslashes in such patterns are doubled. A pattern that already holds a backslash before a quote changes only in source text: "^don\\'t$" becomes r"^don\'t$". This affects string field patterns, propertyNames key patterns, and StringConstraints written under --field-constraints or --use-annotated. Python's re matches the same values, so validation does not change. However, the pattern stored in constr or StringConstraints, and the pattern that model_json_schema() publishes (for example in FastAPI OpenAPI docs), no longer has the extra backslash. The generated source text for these fields also changes, so snapshot tests or committed generated code will show differences after regenerating (Keep a regex holding a quote unchanged in the pattern literal #6790)

This analysis was produced by the release draft workflow

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.96.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A pattern holding a quote is published with an extra backslash

2 participants