datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Backslash in docstrings are not escaped

Open oefe opened this issue 1 year ago • 0 comments
trafficstars

Describe the bug When generating (class) docstrings, special characters such as backslash are not properly escaped.

This causes a warning in type checkers such as pyright/Pylance, and may cause a syntax error in future Python versions.

To Reproduce

Example schema:

{
  "openapi": "3.0.0",
  "components": {
    "schemas": {
      "Example": {
        "description": "Observe the backslash \\ in this line",
        "type": "object"
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input example.json --use-schema-description

Actual behavior The backslash in the produced docstring is not escaped:

class Example(BaseModel):
    """
    Observe the backslash \ in this line
    """

For example, in Pylance, this will generate the warning reportInvalidStringEscapeSequence:

Unsupported escape sequence in string literal

Expected behavior The backslash should be escaped, like this:

class Example(BaseModel):
    """
    Observe the backslash \\ in this line
    """

Version:

  • OS: macOS 14.2.1
  • Python version: 3.12.1
  • datamodel-code-generator version: 0.25.2

Additional context I only checked class docstrings, but it could affect field docstrings as well. This is not limited to backslashes. An unescaped triple quote even causes a black parsing error.

oefe avatar Jan 14 '24 09:01 oefe