replay 'apply' with extended call

Peter Otten __peter__ at web.de
Mon Oct 25 02:40:00 EDT 2004


Alan G Isaac wrote:

> Consider an example due to Mertz (in Text Processing in Python):
> apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))
> This allows one to supply a list of functions and a tuple of arguments
> to produce a list evaluating each function with those arguments.
> 
> But 'apply' is deprecated in favor of extended call syntax.
> What is the equivalent with extended call syntax?

The literal translation would be:

>>> def apply_each(fns, *args, **kw):
...     return [fn(*args, **kw) for fn in fns]
...
>>> times2 = 2 .__mul__
>>> times4 = 4 .__mul__
>>> apply_each([times2, times4], 3)
[6, 12]

But nobody would bother defining such an apply_each() function anymore.
Instead you can use a list comprehension directly:

>>> [f(3) for f in [times2, times4]]
[6, 12]


Peter




More information about the Python-list mailing list