The code for func1 is equivalent to this
def func1() -> str:
print('func1 was called')
return 'some value here'
func1 = func1()
It could be useful to define a constant value without cluttering the global namespace with the code necessary to compute the value. For example
def VALUE():
... # some complicated computation
return some_expression
VALUE = VALUE()
So it demonstrates how one can abuse Python's function syntax to build a single value. There are many such possibilities in Python. Recently, I shared
a snippet demonstrating how on can abuse the class syntax to build a single dictionary.
Another similar idea I'm using sometimes is a small class
fargs
that represent function arguments. That is to say the fargs object stores the arguments and the keyword arguments of a function call and nothing else. It can then be used to call a function. Here is the class
from functools import partial
class fargs:
"""Object representing arguments of a function call"""
__slots__ = ("args", "kwargs")
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, func):
return func(*self.args, **self.kwargs)
def partial(self, func):
return partial(func, *self.args, **self.kwargs)
if __name__ == '__main__':
def test(n, fruit='apple'):
print(f'The monkey ate {n} {fruit}s')
x = fargs(3, fruit='banana')
x(test)
@fargs()
def func1():
print('func1 was called')
return('some value')
print(func1)
So instead of
@lambda _: _()
, you could use
@fargs()
to achieve the same effect.
Output:
The monkey ate 3 bananas
func1 was called
some value