1

I would like to create a lambda that raises ValueError if its input is a non-empty list. Based on the answer proposed here, I implemented it as follows:

f = lambda x: (_ for _ in ()).throw(ValueError()) if len(x) != 0 else []

(Note that the return value [] when x is an empty list is not important here, I just had to put something to have a complete if-else statement.)

That works as intended, but the code looks a bit cryptic. Is there any nicer way to write the above? I am thinking about using x somehow in the generator (_ for _ in ()) but am not able to see straightforwardly how to do so in order to get the desired result.

MikeL
  • 2,369
  • 2
  • 24
  • 38

1 Answers1

1

The proper solution (the ones mentionned in the post you linked to are all complete WTF) is dead simple and pretty obvious: don't use a lambda. "Lambdas" are just syntactic sugar for proper function definitions (they ARE functions, period), used when you only need a very simple one-shot callback. You can pass a proper function (or just any callable) wherever you use a lambda. IOW what you want is:

def check_non_empty(lst):
    if not lst:
        raise ValueError("list should not be empty")
    return lst
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thank you. Indeed, I would feel more comfortable with a proper function as well --- lambda was a wrong choice. – MikeL Mar 30 '20 at 12:27