2

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

hi15
  • 2,113
  • 6
  • 28
  • 51
  • 3
    Did you try any particular way of writing it? Did you find something unsatisfactory about your way of writing it? – Karl Knechtel Jul 05 '22 at 22:43
  • @KarlKnechtel this is what I have in mind (updated the question) – hi15 Jul 05 '22 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`) – chepner Jul 05 '22 at 22:52
  • That's a typo; it should be `... if 'mean' in d else ...`. – chepner Jul 05 '22 at 23:02
  • Does https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator help? – Karl Knechtel Jul 05 '22 at 23:07
  • The Pythonic way is to not use assert at all. The assert should be used to validate algorithm correctness, or used in unit tests. It should not be used to validate input data. – Keith Jul 06 '22 at 02:21
  • @Keith Where do they say that it's input data? – Kelly Bundy Jul 06 '22 at 02:56
  • @KellyBundy I inferred from the code structure. You can't remove those assertions and keep working, meaningful code. – Keith Jul 06 '22 at 05:15

1 Answers1

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
Kache
  • 15,647
  • 12
  • 51
  • 79