简体   繁体   English

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

[英]mypy - Item "None" of "Optional[CustomAttrsModel]" has no attribute "country"

When I run mypy checkings I am getting an error.当我运行 mypy 检查时,出现错误。 I am no able to ignore it or turn it off the strict optional checking.我无法忽略它或将其关闭严格的可选检查。 It there a way to solve this.它有办法解决这个问题。

Here is the line that is throwing the error:这是引发错误的行:

 if tree.data.attributes.custom != JAPAN:

where attributes is declared as:其中attributes声明为:

class TreeAttributesModel(BaseModel):
    id: Optional[TreeId]
    name: Optional[str] = None
    status: StatusEnum
    custom: Optional[CustomAttrsModel] = None

and CustomAttrsModel is declared as it follows:并且CustomAttrsModel声明如下:

class CustomAttrsModel(BaseModel):
    seller: Optional[str]
    buyed_at: Optional[datetime]
    country: Optional[Union[CountryEnum, str]]

Could you please help me with this?你能帮我解决这个问题吗?

I had to tweak your snippets a bit to get a MWE, but here we go :我不得不稍微调整一下你的片段以获得 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

The message is: just use assert something is not None whenever something is Optional ;)消息是:只要somethingOptional的,就使用assert something is not None ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM