Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any operator.unpack in Python?

Is there any built-in version for this

def unpack(f, a):
    return f(**a) #or ``return f(*a)''

Why isn't unpack considered to be an operator and located in operator.*?

I'm trying to do something similar to this (but of course want a general solution to the same type of problem):

from functools import partial, reduce
from operator import add
data = [{'tag':'p','inner':'Word'},{'tag':'img','inner':'lower'}]
renderer = partial(unpack, "<{tag}>{inner}</{tag}>".format)
print(reduce(add, map(renderer, data)))

as without using lambdas or comprehensions.

like image 666
SlimJim Avatar asked Jan 29 '26 02:01

SlimJim


1 Answers

That is not the way to go about this. How about

print(''.join('<{tag}>{inner}</{tag}>'.format(**d) for d in data))

Same behavior in a much more Pythonic style.

Edit: Since you seem opposed to using any of the nice features of Python, how about this:

def tag_format(x):
    return '<{tag}>{inner}</{tag}>'.format(tag=x['tag'], inner=x['inner'])
results = []
for d in data:
    results.append(tag_format(d))
print(''.join(results))
like image 134
Abe Karplus Avatar answered Jan 31 '26 16:01

Abe Karplus