-1

I have a named lambda expression like this one:

expr1 = lambda x: x > 3

For some reasons, along the code I check some flags and might do this:

expr2 = lambda x: expr1(x) and x % 2 == 0

So, I am defining a more restrictive lambda expression based on my needs.

I've seen this post about naming lambdas that explains how they are not pythonic at all.

What is a better way to define functions that may get more conditions along the code?

Pendulun
  • 11
  • 3
  • 1
    If you want a longer condition, you want a longer condition. Sometimes there's no way around that. For replacing the `lambda` though, you'd just use a normal function defined using `def`,. – Carcigenicate Jul 11 '23 at 12:56
  • 1
    It's not pythonic to use lambdas where regular `def` functions would do. *That's* the problem. Not combining functions, that's fine. – deceze Jul 11 '23 at 12:58

1 Answers1

0

In general, you would use def to define a function.

In your specific case, something like the following would work:

def greater_than_3(x):
    return x > 3

def even(x):
    return x % 2 == 0

def my_test(x):
    return (greater_than_3(x) and even(x))

Then you just need to call my_test(x) when required. It returns True if x satisfies both of the conditions, False if not.

You there defined 3 functions instead of only 2 in your code, but as you do not seem to sure about whether or not you will add more conditions later in your code, this allows you to improve readability.

Shenoz
  • 18
  • 3