Pergunta

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?

Foi útil?

Solução

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top