Hacker News new | comments | show | ask | jobs | submit login

Once you do decide to use an assert in python, there are a couple things to consider. The first is to make sure you are expressive in your message. Your assert may very well hit one day, and it may only occur at the most unpredictable times, so you'll want to make sure you have enough information to see why the assert failed. To use the OP's example:

  assert x > 0, "x is not zero or negative"
When this fails, you're going to be at a loss to understand what actually happened. If you change the message to something like the following, you're going to have a much easier time tracing through your program to understand why your constraint was violated:

  assert x > 0, "Expected positive x, got: %d" % x
Once you get in the habbit of this, you'll quickly run up against style-guide imposed line limits. My usual trick here is to use parenthesis and let python's automatic string concatenation work its wonders, but you have to be careful because

   assert (x > 0, "This is my longer message "
           "for x")
evaluates to a tuple, and thus is always true. Instead only use parens around the message:

   assert x > 0, ("This is my longer message "
                  "for x")
Lastly, don't use asserts in tests. Use the standard unittest library which will do a much better job explaining what was received, what was expected, and what the difference between them is.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact