How to: Make Python Asserts

A few very quick notes about python assertions. Most of this is probably already known / obvious to everyone but maybe this will help someone.

1. You can make your assertions more user friendly (for when they trigger and show up in logs) by passing a second argument as a string. For example:
assert type(id) is IntType, “id is not an integer: %s” % id
Will then show up as AssertionError: “id is not an integer: foo” instead of just AssertionError in logs.
2. DON’T USE PARENTHESES TO DO THIS. For example the following is very wrong:
assert (type(id) is IntType, “id is not an integer: %s” % id)
The assert evaluates this as an assertion of a single tuple object, which will always be true. Thus your assertion is useless. Some versions of python spit out runtime errors to help you find these.
3. If you’re worried about performance and you’re not using asserts as part of your security model, you can run python with -O option, which removes all assert statements.

Share

Tags

Similar Articles

The World's Most Powerful Mobile Data Collection Platform

Start a FREE 30-day CommCare trial today. No credit card required.

Get Started

Learn More

Get the latest news delivered
straight to your inbox