datamodel-code-generator
datamodel-code-generator copied to clipboard
Mypy failure from schema with multiple properties where one has same name as $ref
Describe the bug If multiple properties use the same $ref, with one of those properties having the same name as the $ref, the generated code fails mypy checks with a [name-defined] error.
To Reproduce
Example schema:
identifier.json
:
{
"$schema": "http://json-schema.org/schema",
"title": "Identifier",
"type": "object",
"properties": {
"identifier_name": {
"type": "string"
}
}
}
example.json
:
{
"$schema": "http://json-schema.org/schema",
"title": "Example",
"type": "object",
"properties": {
"identifier": {
"$ref": "identifier.json"
},
"another_identifier": {
"$ref": "identifier.json"
}
}
}
Generated code:
identifier.py
:
# generated by datamodel-codegen:
# filename: identifier.json
# timestamp: 2022-09-02T12:22:46+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel
class Identifier(BaseModel):
identifier_name: Optional[str] = None
example.py
:
# generated by datamodel-codegen:
# filename: example.json
# timestamp: 2022-09-02T12:22:46+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel
from . import identifier
class Example(BaseModel):
identifier: Optional[identifier.Identifier] = None
another_identifier: Optional[identifier.Identifier] = None
Used commandline:
$ datamodel-codegen --input example/ --output example_output/ --field-constraints
$ mypy example_output/ --show-error-codes
example_output/example.py:16: error: Name "identifier.Identifier" is not defined [name-defined]
Found 1 error in 1 file (checked 3 source files)
Expected behavior
I would expect the generated code to pass mypy checks with no errors. Since the error appears to be caused by the from . import identifier
import, changing this to be from . import identifier as identifier_
would work.
Version:
- OS: MacOS
- Python version: 3.8.6
- datamodel-code-generator version: 0.13.1
Additional context N/A