為不同檔案中的類指定型別提示時如何解決遞回問題
模型1.py
from models2 import Second
@dataclass
class First:
attribute: Second
模型2.py
from models1 import First
@dataclass
class Second:
attribute: First
SentInvoice在實際代碼中,我想將User模型拆分為不同的檔案。
class User(models.Model):
user_id = fields.BigIntField(index=True, unique=True)
username = fields.CharField(32, unique=True, index=True, null=True)
first_name = fields.CharField(255, null=True)
last_name = fields.CharField(255, null=True)
language = fields.CharField(32, default="ru")
balance: Balance = fields.OneToOneField("models.Balance", on_delete=fields.CASCADE)
sent_invoice: fields.OneToOneNullableRelation["SentInvoice"] # here
registered_user: RegisteredUser
@classmethod
async def create(cls: Type[MODEL], **kwargs: Any):
return await super().create(**kwargs, balance=await Balance.create())
class SentInvoice(models.Model):
amount = fields.DecimalField(17, 7)
shop_id = fields.CharField(50)
order_id = fields.CharField(10, null=True)
email = fields.CharField(20, null=True)
currency = fields.CharField(5, default="RUB", description="USD, RUB, EUR, GBP")
user: fields.ForeignKeyRelation[User] = fields.ForeignKeyField("models.User", on_delete=fields.CASCADE) # here
created_invoice: fields.OneToOneNullableRelation[CreatedInvoice]
async def send(self) -> CreatedInvoice:
cryptocloud = config.payment.cryptocloud
async with aiohttp.ClientSession(headers={"Authorization": f"Token {cryptocloud.api_key}"}) as session:
async with session.post(cryptocloud.create_url, data=dict(self)) as res:
created_invoice = await CreatedInvoice.create(**await res.json(), sent_invoice=self)
return created_invoice
uj5u.com熱心網友回復:
您需要使用兩種特定于 python 中的型別提示的技術,1)前向參考TYPE_CHECKING,以及 2) 在警衛中匯入型別(例如,查看這篇文章以獲得對其含義的更長解釋)。第一個允許您在運行時參考解釋器不知道的型別,后者在“型別檢查背景關系”中決議型別。
長話短說:
模型1.py
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models2 import Second
@dataclass
class First:
attribute: "Second"
模型2.py
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from models1 import First
@dataclass
class Second:
attribute: "First"
執行具有python3.8或更高版本的檔案應該沒有任何問題[1],并且可以python3.7與import 一起__futures__作業。在檔案上運行mypy也應該沒有任何問題:
$ mypy models1.py models2.py
Success: no issues found in 2 source files
[1]正如評論所指出的那樣,創建您的First/Second類的實際實體也將通過型別檢查是不可能的,但我認為這是一個玩具示例,您的真實代碼具有例如屬性之一作為Optional.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475133.html
