melatonin15
melatonin15

Reputation: 2269

assert inside if else condition in python

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

Upvotes: 0

Views: 852

Answers (1)

Kache
Kache

Reputation: 16667

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

Upvotes: 1

Related Questions