Python: generic lazy lambda function via argument expansion

Without doubt, the *-operator for argument gathering/scattering/expansion/unpacking/splat in Python is a very useful tool (as in any other language). Today, I used this language feature in a rather dirty context: combined with the lambda keyword, we can use it for creating an anonymous function accepting any combination of arguments:

>>> noop = lambda *a, **b: None

*a collects positional arguments in variable a, **b collects keyword arguments in b. The function does not use any of the arguments. It always returns None.

noop() can now be called in any way:

>>> print noop(1, 2, 3, arg=1, peter="wurzel")
None
>>> print noop()
None

This can be useful for disabling a certain functionality during run-time of a Python program (aka monkey-patching), as in e.g.:

>>> import multiprocessing.forking
>>> multiprocessing.forking.Popen.poll = lambda *a, **b: None

In many situations, I agree,

def noop(*a, **b):
    pass

might be cleaner.

Leave a Reply

Your email address will not be published. Required fields are marked *

Human? Please fill this out: * Time limit is exhausted. Please reload CAPTCHA.