Can I unpack/destructure a typing.NamedTuple?

4.4k Views Asked by At

This is a simple question so I'm surprised that I can't find it asked on SO (apologies if I've missed it), and it always pops into my mind as I contemplate a refactor to replace a tuple by a NamedTuple.

Can I unpack a typing.NamedTuple as arguments or as a destructuring assignment, like I can with a tuple?

1

There are 1 best solutions below

2
On BEST ANSWER

Yes you certainly can.

from typing import NamedTuple

class Test(NamedTuple):
    a: int
    b: int

t = Test(1, 2)

# destructuring assignment
a, b = t
# a = 1
# b = 2

def f(a, b):
    return f"{a}{b}"

# unpack
f(*t)
# '12'

Unpacking order is the order of the fields in the definition.