Use namedtuple instead of tuple with typing.optional

276 Views Asked by At

How can I use namedtuple with typing.optional instead of this tuple ? I want to to call the function in the format of result_final(power=Stats(min=12, max=None)) Thank you. I tried with Stats = namedtuple('Stats', [Optional[int], Optional[int]])

from typing import Optional, Tuple
Stats = Tuple[Optional[int], Optional[int]]  # min, max

def result_final(power: Stats):
    min, max = power
    print("min:", min, "max: ", max)
print(result_final(power=(12, None)))

# namedTuple to have result_final(power=Stats(min=12, max=None))
1

There are 1 best solutions below

2
Hitobat On BEST ANSWER

If it's Python 3 you can do the following.

from typing import NamedTuple

class Stats(NamedTuple):
    min: Optional[int]
    max: Optional[int]

See docs for further details: https://docs.python.org/3.7/library/typing.html#typing.NamedTuple