I have come across some code that uses lambda expressions on multiple occasions to pass around classes.
class Clazz:
def __init__(self, a, b=-1):
self.a = a
self.b = b
def __str__(self):
return f'Clazz: {self.a}; {self.b}'
clazz_fn1 = lambda a: Clazz(a) # o1_fn is than passed to some other function ...
c1 = clazz_fn1(1) # ... where the Clazz object is initialized
print(c1)
Is there any advantage in using a the lambda
keyword over just passing the class name?
clazz_fn2 = Clazz
c2 = clazz_fn2(2)
print(c2)
The only advantage that comes to my mind, is that lambda functions offer the possibility to pass further arguments along:
clazz_fn3 = lambda a: Clazz(a, b=42)
c3 = clazz_fn3(3)
print(c3)
On the other hand, it is my understanding that using lambda functions is not something that is generally recommended (see e.g. this posts: Guido van Rossum interview, post on overusing of lambda expressions... still this discussion seems to be mostly in favour of lambda expressions).
I am also aware of the question on why to use lambda functions, but using lambda functions to pass around classes as described above does not seem to be the typical use case for the lambda syntax that is covered by this more general discussion.
So are there further differences between the two options or is this a purely stylistic choice?