pythonpython-collections

Use namedtuple instead of tuple with typing.optional


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))

Solution

  • 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