Search code examples
pythonpython-3.xcoding-style

What is more pythonic: trivial lambda or None?


When a function accepts a function argument (or a class has a function slot), there is a choice between two approaches:

def foo(..., my_func=None, ...):
    ...
    if my_func:
        my_func(...)
    ...

and

def foo(..., my_func=(lambda ...: None), ...):
    ...
    my_func(...)
    ...

What is more Pythonic/clear/readable?

What is faster - an extra boolean check or a trivial function call?


Solution

  • When using this:

    >>> def bar():
    ...     print("Goodbye, World!")
    ...
    

    I find this very readable:

    >>> def foo(my_func = lambda : None):
    ...     my_func()
    ...
    >>> foo()
    >>> foo(bar)
    Goodbye, World!
    

    I find this pointlessly annoying

    >>> def baz(my_func = None):
    ...     if my_func is not None:
    ...         my_func()
    ...
    >>> baz()
    >>> baz(bar)
    Goodbye, World!
    

    Try to keep None checks out of your life. Use None when you want it to do what it does well: blow up in your face. Don't ask it to be quiet. One way or another it's going to create annoying noise if you use it.

    What is faster - an extra boolean check or a trivial function call?

    Why, in Gods name, do you care?


    For the record, I find this readable but overly permissive:

    >>> def buz(my_func = lambda **k:None):
    ...     my_func()
    ...
    >>> buz(bar)
    Goodbye, World!