Search code examples
pythonnamedtupleargument-unpackingdestructure

Can I unpack/destructure a typing.NamedTuple?


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?


Solution

  • 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.