When I run mypy checkings I am getting an error. 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:
JavaScript
x
2
1
if tree.data.attributes.custom != JAPAN:
2
where attributes
is declared as:
JavaScript
1
6
1
class TreeAttributesModel(BaseModel):
2
id: Optional[TreeId]
3
name: Optional[str] = None
4
status: StatusEnum
5
custom: Optional[CustomAttrsModel] = None
6
and CustomAttrsModel
is declared as it follows:
JavaScript
1
5
1
class CustomAttrsModel(BaseModel):
2
seller: Optional[str]
3
buyed_at: Optional[datetime]
4
country: Optional[Union[CountryEnum, str]]
5
Could you please help me with this?
Advertisement
Answer
I had to tweak your snippets a bit to get a MWE, but here we go:
JavaScript
1
35
35
1
import enum
2
import dataclasses
3
4
from datetime import datetime
5
from typing import Optional, Union
6
7
8
class StatusEnum(enum.Enum):
9
OK = enum.auto()
10
NOK = enum.auto()
11
12
class CountryEnum(enum.Enum):
13
JAPAN = enum.auto()
14
RAPTURE = enum.auto()
15
16
@dataclasses.dataclass
17
class TreeAttributesModel:
18
id: Optional[str]
19
name: Optional[str] # = None had to remove default, attribs w/o default cannot follow attribs w/ one
20
status: StatusEnum
21
custom: Optional[CustomAttrsModel] = None
22
23
@dataclasses.dataclass
24
class CustomAttrsModel:
25
seller: Optional[str]
26
buyed_at: Optional[datetime]
27
country: Optional[Union[CountryEnum, str]]
28
29
custom = CustomAttrsModel(seller="test", buyed_at=None, country=CountryEnum.JAPAN)
30
attribs = TreeAttributesModel(id="test", name="test", status=StatusEnum.OK, custom=custom)
31
32
assert attribs.custom is not None # this is typed as being optional, so make sure it isn't None
33
assert attribs.custom.country is not None # same as above
34
result = attribs.custom.country != CountryEnum.JAPAN
35
The message is: just use assert something is not None
whenever something
is Optional
;)