Empty functions and a few very simple functions can always be replaced with the return value when used in an assignment (e.g. x = f()) or removed completely when acting as a procedural function call.
def f1(): ...
def f2(): pass
def f3(): return
def f4(): return None
def f5(): return 123
def f6(): return 60 * 60 * 24
def f7(hours=24): # Replace/remove only when called without args: `f7()`
return 60 * 60 * hours
It might seem like no one would define empty functions, but I sometimes do the following to make debugging easier without adding vulnerabilities in production:
if __debug__:
def f(): ... do something ...
else:
def f(): pass
With this optimization, I could have the best of both worlds (easy debugging during development and zero added overhead to production).
I also use this pattern:
def f(data, cb: Callable = lambda *args: None):
...
r = cb(data)
...
Instead of this:
def f(data, cb: Callable | None = None):
...
if cb:
r = cb(data)
else:
r = None
...
The function def identity(x): return x can simplify the logic in some cases when I use functional programming. For example, when delegating which function should be passed to map() or filter().
Empty functions and a few very simple functions can always be replaced with the return value when used in an assignment (e.g.
x = f()) or removed completely when acting as a procedural function call.It might seem like no one would define empty functions, but I sometimes do the following to make debugging easier without adding vulnerabilities in production:
With this optimization, I could have the best of both worlds (easy debugging during development and zero added overhead to production).
I also use this pattern:
Instead of this:
The function
def identity(x): return xcan simplify the logic in some cases when I use functional programming. For example, when delegating which function should be passed tomap()orfilter().