Azure / Azure/typespec-azure

typespec-python: inconsistent backslash escaping in generated model docstrings (\W becomes \W in attribute docstring)

Open
#4,325 0 comments 0 reactions 0 assignees View on GitHub
bug emitter:python needs-area
Dominant language
TypeScript
Stars
27
Forks
90
Avg merge
1d 22h
Merged PRs (30d)
156

Description

### Context
When generating Python SDK models from TypeSpec docs containing regex text like `[\\W_]`, the generated `_models.py` contains inconsistent escaping across two docstring emission paths.

### Expected behavior
Both generated docstrings should preserve a literal backslash in Python source by emitting `\\W` in code text (so runtime docstring content is `\W`).

### Actual behavior
For the same source description, generation produces:
- class `:ivar:` docstring: `Regex match [\\W_]` (correct)
- field attribute inline docstring: `Regex match [\W_]` (incorrect in source text, triggers `SyntaxWarning: invalid escape sequence '\\W'`)

### Repro source (TypeSpec)
In the AKS TypeSpec, the source doc string includes:

`Regex match [\\W_]`

### Intermediate output check
Generated OpenAPI/Swagger JSON preserves the content correctly (JSON string shows `\\\\W`, value is `\\W`).

### Generated Python output check
In generated `models/_models.py`, two occurrences differ for the same field description:
- one escaped (`[\\\\W_]` in bytes / ` [\\W_] ` in source)
- one unescaped (`[\\W_]` in bytes / ` [\W_] ` in source)

This indicates escaping is applied in one docstring code path but not the other.

### Why this matters
The unescaped form in a normal Python string literal causes warnings on import under newer Python versions:

`SyntaxWarning: invalid escape sequence '\\W'`

### Request
Please make escaping consistent for all generated Python docstring outputs (including inline field docstrings) so backslashes in doc text are safely escaped.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the AKS TypeSpec case and inspecting generated models/_models.py, comparing the class :ivar: docstring with the inline field docstring for the same description. Trace the two docstring emission paths and verify that both preserve the literal backslash in generated source without a Python invalid-escape warning.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
58/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.