datamodel-code-generator
datamodel-code-generator copied to clipboard
Relative imports paths when generating multiple models
When generating schemas with a directory of JSON-Schemas as --input the relative import paths will be problematic. I had a complex use-case where pydantic threw an error when attempting to import such a generated model. But maybe I'm missing something.
So, e.g. if you have a structure like
- src
- pkg1
- a.py
- pkg2
- b.py
a module would look like this:
from ..pkg2 import b
from pydantic import BaseModel
class A(BaseModel):
bb: b.B | None = None
Which is fine in principle. But when attempting to import e.g. class A which references to an enum, pydantic throws an error similar to B has no attribute B. So this might be more an issue of pydantic. I would suggest to change the relative import to import the model directly (or at least have a flag for this) anyway.
from ..pkg2.b import B
from pydantic import BaseModel
class A(BaseModel):
bb: B | None = None
@lord-haffi
So this might be more an issue of pydantic. I would suggest to change the relative import to import the model directly (or at least have a flag for this) anyway.
I'm sorry. I need help understanding your faced problem. Can you explain in more detail?
Can you resolve the Relative imports problem for your suggestion?
I tried your example. I got the relative imports errors.
>>> from pkg1.a import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/koudai/PycharmProjects/pythonProject/output/pkg1/a.py", line 11, in <module>
from ..pkg2 import b
ImportError: attempted relative import beyond top-level package
>>> from pkg1.a import A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/koudai/PycharmProjects/pythonProject/output/pkg1/a.py", line 11, in <module>
from ..pkg2.b import B
ImportError: attempted relative import beyond top-level package
>>>
Do we need __init__.py in src directory to detect src as a package?
Sorry for my late response. I have not so much time and as I commented in #1684, I monkey-patched the function for me, so it doesn't have prio for me.
I don't know what you did there. As for example this StackOverflow answer explains, these kind of import errors usually appear if you don't "call" the package correctly. But judging by the paths of error messages you posted, I think that /output is missing an __init__.py file if that is what you meant. But I don't know how you did this since in my experiments it always generated such an __init__.py file.
Plus, I don't know if the error I encountered that time is still present. Anyway, I don't like this import-style and would prefer the explicit import-style.
Fixed by #1983