Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - notation for redundant lambda parameters

I am trying to build a function

f(x, y, z)

where neither x nor y have any impact on the result. Nonetheless, they must be passed to the function, as the passing is done by a library. I would like to:

  • solve this using a lambda expression, and
  • ensure that anyone reading my code will immediately know that x and y are redundant.

As I have gathered, using the underscore character for redundant return values from multiple-value-returning functions is common practice, e.g.

a, _, c, d, _, _ = return_six_things(),

however, trying

f = lambda _, _, z: some_operation(z)

crashes with the exception warning the author about using 'duplicate arguments' (two underscore characters).

Are there any other options?

P.S. to avoid the XY problem, the reason I want to use lambdas is to save a few source code characters. I would love to use them anyway, but declaring that "these parameters will not be used" is more important for me.

like image 363
Captain Trojan Avatar asked Jun 09 '26 00:06

Captain Trojan


2 Answers

I'd use a double underscore (__) for the second unused argument:

f = lambda _, __, z: some_operation(z)
like image 153
Mureinik Avatar answered Jun 10 '26 14:06

Mureinik


Options:

# pass in z as a keyward argument
# like this: f(x,y,z=1)
f = lambda *_,z: some_operation(z)

#Or:
# pass in any number of arguments and only use the last argument 
f = lambda *z: some_operation(z[-1])
like image 42
fusion Avatar answered Jun 10 '26 12:06

fusion