1
\$\begingroup\$

I am checking data output in some testing code, and only some fields can be None, but I think this can be better:

for key in data[0].keys():
        self.assertIn(key, data_model)
        if data[0][key] is None:
            self.assertTrue('rate' in key or 'percentage' in key or 'ratio' in key)
            continue
        self.assertIsInstance(data[0][key], data_model[key])

Mostly I don't like the ... or ... in the assertTrue

\$\endgroup\$
5
\$\begingroup\$

A few things:

  • your indentation looks weird

  • you could store data[0] in some variable with a relevant name.

  • you could iterate over both keys and values with iteritems() /items()

  • you do not need continue here. A simple else would do the trick and is more explicit.

  • The line you don't quite like could be replaced by something like :

self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))

The resulting code would be :

first_data = data[0]
for key, val in first_data.items():
    self.assertIn(key, data_model)
    if val is None:
        self.assertTrue(any(w in key for w in ('rate', 'percentage', 'ratio')))
    else:
        self.assertIsInstance(val, data_model[key])
\$\endgroup\$
  • \$\begingroup\$ Thanks - any was exactly what I wanted, just hadn't thought of it. Also good suggestion about items(), and I agree about the else \$\endgroup\$ – user3610360 Jun 30 '16 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.