3

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?

Cai
  • 1,726
  • 2
  • 15
  • 24

1 Answers1

4

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.

Cai
  • 1,726
  • 2
  • 15
  • 24
  • 1
    Upvoted because technically correct, but this seems prone to error. I wish python supported object destructuring like JS: `{ a, b } = t` where code can't break from misordering. – Ben Jones Aug 28 '23 at 22:46