assert inside if else condition in python

Viewed 113

I want to check the following using assert.

If: key mean is in dictionary d then it should have length equal to N. else: sigma should not be None.

What is the concise and pythonic way to write this assertion?

I tried this:

if "mean" in d:
    assert len(d["mean"]) == N
else:
    assert sigma is not None

1 Answers

A bit more code style thing, but if you want it to read like "it has one assert", I'd suggest:

has_expected_mean_len = 'mean' in d and len(d['mean']) == N
has_sigma = 'mean' not in d and sigma is not None

assert has_expected_mean_len or has_sigma
Related