python: alternative to anonymous functions python: alternative to anonymous functions python-3.x python-3.x

python: alternative to anonymous functions


You don't need anonymous functions. Also, memoization has been done better than this, there's probably no reason for you to roll your own.

But to answer the question: You can use your class as a decorator.

@Calculationdef f2():    ...

This simply defined the function, wraps it in Calculation and stored the result of that as f2.The decorator syntax is defined to be equivalent to:

_decorator = Calculation # a fresh identifier# not needed here, but in other cases (think properties) it's usefuldef f2():    ...f2 = _decorator(f2)


The alternative to an anonymous function is a non-anonymous function. An anonymous function is only anonymous in the context where it was defined. But it is not truly anonymous, because then you could not use it.

In Python you make anonymous functions with the lambda statement. You can for example do this:

output = mysort(input, lambda x: x.lastname)

The lambda will create a function, but that function has no name in the local space, and it's own name for itself is just '<lambda>'. But if we look at mysort, it would have to be defined something like this:

def mysort(input, getterfunc):    blahblahblah

As we see here, in this context the function isn't anonymous at all. It has a name, getterfunc. From the viewpoint of this function it does not matter if the function passed in are anonymous or not. This works just as well, and is exactly equivalent in all significant ways:

def get_lastname(x):    return x.lastnameoutput = mysort(input, get_lastname)

Sure, it uses more code, but it is not slower or anything like that. In Python, therefore anonymous functions are nothing but syntactic sugar for ordinary functions.

A truly anonymous function would be

lambda x: x.lastname

But as we don't assign the resulting function to anything, we do not get a name for the function, and then we can't use it. All truly anonymous functions are unusable.

For that reason, if you need a function that can't be a lambda, make it an ordinary function. It can never be anonymous in any meaningful way, so why bother making it anonymous at all? Lambdas are useful when you want a small one-line function and you don't want to waste space by defining a full function. That they are anonymous are irrelevant.


A closure can be a succinct alternative to writing a class such as the one in your example. The technique involves putting a def inside another def. The inner function can have access to the variable in the enclosing function. In Python 3, the nonlocal keyword gives you write access to that variable. In Python 2, you need to use a mutable value for the nonlocal variable in order to be able to update it from the inner function.

About the question regarding anonymous functions, the language intentionally pushes you back to use def for anything more complicated than a lambda can handle.