Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a namedtuple onto a function?

In Python, if you have a dictionary

d = {'foo': 1, 'bar': False}

You can apply this onto a function that accept foo and bar keyword arguments by

def func(foo, bar):
    # Do something complicated here
    pass

func(**d)

But if instead, I wanted to call func with the namedtuple defined below:

from collections import namedtuple
Record = namedtuple('Record', 'foo bar')
r = Record(foo=1, bar=False)
func(r)   # !!! this will not work

What's the syntax for this?

like image 575
fatuhoku Avatar asked Oct 31 '13 13:10

fatuhoku


People also ask

How do I access Namedtuple elements?

The accessing methods of NamedTuple From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes. The NamedTuple converts the field names as attributes.

How do we need to import Namedtuple?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.

Can Namedtuple be modified?

Since a named tuple is a tuple, and tuples are immutable, it is impossible to change the value of a field.


1 Answers

A namedtuple instance has a ._asdict() method:

func(**r._asdict())

but if the namedtuple attributes are in the same order as the arguments of the function, you could just apply it as a sequence instead:

func(*r)

Here the two values of the namedtuple are applied, in order, to the keyword arguments in the function. Those two arguments can be addressed as positional arguments still, after all!

For your sample function, both work:

>>> def func(foo, bar):
...     print foo, bar
... 
>>> from collections import namedtuple
>>> Record = namedtuple('Record', 'foo bar')
>>> r = Record(foo=1, bar=False)
>>> func(**r._asdict())
1 False
>>> func(*r)
1 False
like image 184
Martijn Pieters Avatar answered Sep 30 '22 00:09

Martijn Pieters