Reputation: 12950
I have been able to have mypy
do a type check on NamedTuple
and use default values for NamedTuple
.
However, I always have an error raised by mypy
when I use default value.
Here is my code (I use Python 3.6)
class TestResult(NamedTuple):
"""To store results of a given Test Case"""
outcome: str
duration: Optional[int] # in seconds
comment: Optional[str]
msg: Optional[str]
TestResult.__new__.__defaults__ = (None,) * 3 # type: ignore # Hack for Python < 3.7
When I do passed_tc = TestResult("Passed")
, I have the following error message
error:Too few arguments for "TestResult"
Anyone got an idea on how to tell mypy
we can have optional arguments and avoid this error?
Upvotes: 1
Views: 1475
Reputation: 64278
Assign the values that need default values with the desired default values. For example:
from typing import NamedTuple, Optional
class Test(NamedTuple):
foo: str
bar: Optional[str] = None
qux: int = 100
t = Test("foo")
I've tested that this works at runtime for both Python 3.6 and 3.7, and confirmed it type-checks as expected using mypy 0.641.
Upvotes: 3