Using 'apply' as a decorator, to define constants

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Aug 22 04:54:27 CEST 2009


On Fri, 21 Aug 2009 15:17:40 -0700, Jonathan Gardner wrote:

>> Unfortunately, apply() has been removed as a built-in in 3.x. I'm not
>> sure if it has been relocated to a module somewhere, there's no mention
>> of such in the docs.
> 
>     apply = lambda f: f()
> 
> It's one of those functions that is easier to define than import.

>>> apply = lambda f: f()
>>> __builtin__.apply(len, 'a')
1
>>> apply(len, 'a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)


It's a little bit more difficult to define it *correctly*. Here's a 
working version of apply:


def apply(object, *args, **kwargs):
    """apply(object[, args[, kwargs]]) -> value

    Call a callable object with positional and keyword arguments.

    >>> apply(max, 'one', 'two', 'three', 'four', key=len)
    'three'

    """
    return object(*args, **kwargs)

Note that this:

* actually does what apply() is supposed to do;
* defines the function name, useful for tracebacks;
* has a docstring, useful for interactive use and documentation;
* includes an example suitable for automated testing with doctest.



-- 
Steven



More information about the Python-list mailing list