Validating statements in lambda in python

I am trying to use statements to show some invariants (mainly in testing) So I want to write something like the following:

values = [ range(10) ] expected_values = [ range(10) ] map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_values)) 

If I use this with unittest.assertEqual, this works fine, but if I want to write this with a statement, it just fails. Is there any way to fix this?

+6
source share
3 answers

Unfortunately, assert is a statement, and the limited lythdas of Pythons do not allow this in them. They also limit things like print .

Here you can use the generator expression.

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

I personally think the following will be more readable

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

From the documentation :

Please note that functions created using lambda forms cannot contain operators.

assert is a statement.

No, you cannot use the assert operator in a lambda expression.

+8
source

In fact, you can:

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

Here are a few confirmations:

 try: assertion_raiser() except AssertionError: print("assertion caught") 
+2
source

Source: https://habr.com/ru/post/903603/


All Articles