Describe the bug
When generating models from the openapi specification and when the names of the schemas contain dots, incorrect imports are generated inside init.py for modules that are actually located in the same directory
Only inside init.py the extra dot in the import statement is added. In other generated .py files, imports are generated correct
To Reproduce
Example schema:
{
"openapi": "3.0.2",
"info": {
"title": "Swagger",
"version": "1.0.17"
},
"paths": {
},
"components": {
"schemas": {
"A.B.C": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"example": 10
},
"reference": {
"$ref": "#/components/schemas/A.B.D.E"
}
}
},
"A.B.D.E": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64",
"example": 10
}
}
}
}
}
}
Used commandline:
$ datamodel-codegen --input swagger.json --output model --input-file-type openapi
Actual behavior
The following file and folder structure was created
.
βββ model/
βββ A/
βββ B/
β βββ D.py
β βββ __init__.py
βββ __init__.py
Code for init.py inside B folder
# generated by datamodel-codegen:
# filename: swagger.json
# timestamp: 2023-10-05T14:48:13+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, Field
from .. import D
class C(BaseModel):
id: Optional[int] = Field(None, example=10)
reference: Optional[D.E] = None
There are one extra '.' in 'from .. import D' statement because module D is in the same directory
Trying to use a class from that init.py and getting error
from model.A.B import C
c = C(id=10)
PS C:\Projects\model-test> python .\test.py
Traceback (most recent call last):
File "C:\Projects\model-test\test.py", line 1, in <module>
from model.A.B import C
File "C:\Projects\model-test\model\A\B\__init__.py", line 11, in <module>
from .. import D
ImportError: cannot import name 'D' from 'model.A' (C:\Projects\model-test\model\A\__init__.py)
Expected behavior
Relative Import inside init.py should not contain an extra dot in situations where reference to a module in the same directory is used
For init.py code from above it expected to look like this
# generated by datamodel-codegen:
# filename: swagger.json
# timestamp: 2023-10-05T14:48:13+00:00
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, Field
from . import D
class C(BaseModel):
id: Optional[int] = Field(None, example=10)
reference: Optional[D.E] = None
Version:
Additional context
I guess such behavior is related to these lines of code in parser/base.py
datamodel-code-generator/datamodel_code_generator/parser/base.py
Lines 688 to 690 in 60256ef
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too