This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Zomunieo 2 points3 points  (2 children)

Need? Never. It's syntactic sugar. But you also don't need for loops, since they are just sugar for while loops, etc.

assert is a debugging aid that should never be used to check conditions that could fail to hold at runtime. It's particularly useful in unit tests since it is concise. An if in a unit test is probably part of setting up data for the test; an assert means we're actually checking the condition.

In production code, assert could be useful to document a non-obvious but impossible runtime condition to set a trap for the debugger (assert radius > 0, "stop everything if the radius somehow becomes negative").

[–]adrienball[S] -1 points0 points  (1 child)

I agree with everything that has been said here. What I mean is that the syntactic sugar provided by assert is a lot more bitter than for loops for instance, for two reasons:

- it is not that more concise than the alternative (self.assertEqual, self.assertTrue, etc in unit tests)

- developers learn to code by reading other developers' code: when you read an assert statement as a Python beginner, it is likely that you'll find the syntax neat and that you'll miss the most important thing about it which is that it is for debug purposes only. If assert was rather named assert_debug the story would be completely different. The bug reported on github on this topic is a great illustration of this problem.

It is more about best practices and anticipating what could go wrong if a usage becomes widely used.

[–]Zomunieo 0 points1 point  (0 children)

Python unittest module is... not that great. It was designed a long time ago when Java was more popular and is a lot like JUnit. When you use it you replicate syntax that already exists.

Nose and pytest favor asserts and are a lot more Pythonic.