Alex Alex - 1 month ago 22
Python Question

checking assertions in a lambda in python

I'm trying to use assertions to show some invariants (mostly in testing)
Thus 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 perfectly fine , but if I want to write this with an assertion it just fails. Is there a way to fix this?

Answer

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))