Python class 属性中的循环导入
Python circular imports in class attributes
我有以下文件:
user.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
company.py
...
from models.user import User
class Company(BaseModel):
user = ForeignKeyField(User, ...)
...
就python而言,这是一个正常的循环导入错误。问题是通常的解决方法(将导入语句放在文件末尾,以不同的方式导入等)在这种情况下不起作用,因为我在定义中使用了 class另一个 class.
的 class 属性
在这种情况下解决循环导入错误的正确方法是什么?
事实证明,正如@PatrickHaugh 指出的那样,这实际上是不可能:
Note that you can't define both of these in the same file as they are written. When you execute the first definition, it will fail because the name of the other class hasn't been defined yet, no matter which you define first. What framework is ForeignKeyField from? It may have tools for circumventing this.
因为我使用 peewee 作为我的 ORM,所以有一个专门为此目的构建的字段:DeferredForeignKey
.
所以,在一天结束时,解决方案是:
user.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
company.py
...
class Company(BaseModel):
user = DeferredForeignKey('User', ...)
...
我有以下文件:
user.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
company.py
...
from models.user import User
class Company(BaseModel):
user = ForeignKeyField(User, ...)
...
就python而言,这是一个正常的循环导入错误。问题是通常的解决方法(将导入语句放在文件末尾,以不同的方式导入等)在这种情况下不起作用,因为我在定义中使用了 class另一个 class.
的 class 属性在这种情况下解决循环导入错误的正确方法是什么?
事实证明,正如@PatrickHaugh 指出的那样,这实际上是不可能:
Note that you can't define both of these in the same file as they are written. When you execute the first definition, it will fail because the name of the other class hasn't been defined yet, no matter which you define first. What framework is ForeignKeyField from? It may have tools for circumventing this.
因为我使用 peewee 作为我的 ORM,所以有一个专门为此目的构建的字段:DeferredForeignKey
.
所以,在一天结束时,解决方案是:
user.py
...
from models.company import Company
class User(BaseModel):
company = ForeignKeyField(Company, ...)
...
company.py
...
class Company(BaseModel):
user = DeferredForeignKey('User', ...)
...