mypy - "Optional[CustomAttrsModel]" 的项目 "None" 没有属性 "country"

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,但是 here we go:

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

信息是:只要 somethingOptional 就使用 assert something is not None ;)