How to avoid circular imports when using models (defined in different modules) which refers to each other?
Just to illustrate there is synthetic example.
# m1.py
from typing import Optional
from pydantic import BaseModel
from m2 import M2
class M1(BaseModel):
foo: Optional[M2]
# m2.py
from typing import Optional
from pydantic import BaseModel
from m1 import M1
class M2(BaseModel):
bar: Optional[M1]
# main.py
from m1 import M1
print(M1(**{'foo': {'bar': None}}))
# ImportError: cannot import name 'M1' from 'm1' in m2.py line 3
The way I found is to modify m1.py like this
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel
class M1(BaseModel):
foo: Optional[M2] # or use ForwardRef('M2') instead of from __future__ import annotations
from m2 import M2
M1.update_forward_refs()
Now main.py works
But the solution is quite counterintuitive, so we we need to modify m1.py while import error happens in m2.py, and if there are more models, with some graph of dependencies, things goes more complicated, not sure we can handle three or more models this way. Also placing import in the bottom of the file violates PEP-8.
Is there some more generalized solution? Maybe place ForwardRef
s in separate module and use it as C-style header files?
ri-gilfanov, mdeous, yanivbeaudoin, shawnwall, escaped and 11 more
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4