checking assertions in a lambda in python

Actually you can:

assertion_raiser = lambda: (_ for _ in ()).throw(AssertionError("My Lambda CAN raise an assertion!"))

Here is some validation:

try:
    assertion_raiser()
except AssertionError:
    print("assertion caught")

Unfortunately, assert is a statement and Pythons limited lambdas don't allow that in them. They also restrict things like print.

You can use a generator expression here though.

assert all(x[0] == x[1] for x in  zip( [run_function(i) for i in values ], expected_values))

I personally think that the following would be more readable

assert all(run_function(i) == j for i,j in zip(inputs, expected_values))

From the documentation:

Note that functions created with lambda forms cannot contain statements.

assert is a statement.

So no, you cannot use the assert statement in a lambda expression.

Tags:

Python