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

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jun 30, 2016 at 11:46
\$\endgroup\$

1 Answer 1

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])
answered Jun 30, 2016 at 12:10
\$\endgroup\$
1
  • \$\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\$ Commented Jun 30, 2016 at 14:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.