Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking assertions in a lambda in python

Tags:

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?

like image 517
Alexander Oh Avatar asked Dec 12 '11 16:12

Alexander Oh


People also ask

How do you check assertions in Python?

The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.

Can you use if statement in lambda Python?

Use lambda function syntax to use an if statement in a lambda function. Use the syntax lambda input: true_return if condition else false_return to return true_return if condition is True and false_return otherwise.

Can lambda expressions contain statements?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.


1 Answers

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))
like image 198
Noufal Ibrahim Avatar answered Oct 03 '22 10:10

Noufal Ibrahim