0

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))
  • I do not understand your question – juanpa.arrivillaga Dec 13 '21 at 21:28
  • @juanpa.arrivillaga i want to use namedtuple instead of Tuple in order to call the result_final in this format: result_final(power=Stats(min=12, max=None)) –  Dec 13 '21 at 21:30
  • You haven't created a `namedtuple` class anywhere. What exactly is the problem? You seem to be aware of named tuples, so what exactly is the problem you are encountering? – juanpa.arrivillaga Dec 13 '21 at 21:31
  • I don't know how to use namedtuple with Optional values –  Dec 13 '21 at 21:32
  • What? Again, **what exactly is the problem**? You don't show any attempt anywhere – juanpa.arrivillaga Dec 13 '21 at 21:32
  • one valubale tipo could be: **forget about typing annotation** and focus on your problem, with the virtues that made Python an easy to use language. Typing is *optional* and basically only adds value to complex or big systems. – jsbueno Dec 13 '21 at 21:42

1 Answers1

0

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

Hitobat
  • 2,847
  • 1
  • 16
  • 12
  • Thank you @Hitobat, there's no way to use directly the NamedTuple ? –  Dec 14 '21 at 06:42
  • I think maybe it's possible. From docs last example is `Employee = NamedTuple('Employee', [('name', str), ('id', int)])`. – Hitobat Dec 14 '21 at 09:16