![](/img/trans.png)
[英]Mypy error Item "None" of "Optional[Dict[str, str]]" has no attribute "get"
[英]mypy - Item "None" of "Optional[CustomAttrsModel]" has no attribute "country"
當我運行 mypy 檢查時,出現錯誤。 我無法忽略它或將其關閉嚴格的可選檢查。 它有辦法解決這個問題。
這是引發錯誤的行:
if tree.data.attributes.custom != JAPAN:
其中attributes
聲明為:
class TreeAttributesModel(BaseModel):
id: Optional[TreeId]
name: Optional[str] = None
status: StatusEnum
custom: Optional[CustomAttrsModel] = None
並且CustomAttrsModel
聲明如下:
class CustomAttrsModel(BaseModel):
seller: Optional[str]
buyed_at: Optional[datetime]
country: Optional[Union[CountryEnum, str]]
你能幫我解決這個問題嗎?
我不得不稍微調整一下你的片段以獲得 MWE,但我們開始吧:
import enum
import dataclasses
from datetime import datetime
from typing import Optional, Union
class StatusEnum(enum.Enum):
OK = enum.auto()
NOK = enum.auto()
class CountryEnum(enum.Enum):
JAPAN = enum.auto()
RAPTURE = enum.auto()
@dataclasses.dataclass
class TreeAttributesModel:
id: Optional[str]
name: Optional[str] # = None had to remove default, attribs w/o default cannot follow attribs w/ one
status: StatusEnum
custom: Optional[CustomAttrsModel] = None
@dataclasses.dataclass
class CustomAttrsModel:
seller: Optional[str]
buyed_at: Optional[datetime]
country: Optional[Union[CountryEnum, str]]
custom = CustomAttrsModel(seller="test", buyed_at=None, country=CountryEnum.JAPAN)
attribs = TreeAttributesModel(id="test", name="test", status=StatusEnum.OK, custom=custom)
assert attribs.custom is not None # this is typed as being optional, so make sure it isn't None
assert attribs.custom.country is not None # same as above
result = attribs.custom.country != CountryEnum.JAPAN
消息是:只要something
是Optional
的,就使用assert something is not None
;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.