0

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

8
  • 3
    Did you try any particular way of writing it? Did you find something unsatisfactory about your way of writing it? Commented Jul 5, 2022 at 22:43
  • @KarlKnechtel this is what I have in mind (updated the question) Commented Jul 5, 2022 at 22:49
  • 3
    This looks fine to me. You could reduce it to a single assert statement using a conditional expression to choose which comparison to assert, but it would be less readable. (assert len(...) == N if mean in d else sigma is not None) Commented Jul 5, 2022 at 22:52
  • That's a typo; it should be ... if 'mean' in d else .... Commented Jul 5, 2022 at 23:02
  • Does stackoverflow.com/questions/394809/… help? Commented Jul 5, 2022 at 23:07

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.