73

I found that Python's assert statement is a good way to catch situations that should never happen. And it can be removed by Python optimization when the code is trusted to be correct.

It seems to be a perfect mechanism to run Python applications in debug mode. But looking at several Python projects like django, twisted and zope, the assert is almost never used. So, why does this happen?

Why are asserts statements not frequently used in the Python community?

Community
  • 1
  • 1
Carlo Pires
  • 4,606
  • 7
  • 32
  • 32

5 Answers5

77

I guess the main reason for assert not being used more often is that nobody uses Python's "optimized" mode.

Asserts are a great tool to detect programming mistakes, to guard yourself from unexpected situations, but all this error checking comes with a cost. In compiled languages such as C/C++, this does not really matter, since asserts are only enabled in debug builds, and completely removed from release builds.

In Python, on the other hand, there is no strict distinction between debug and release mode. The interpreter features an "optimization flag" (-O), but currently this does not actually optimize the byte code, but only removes asserts.

Therefore, most Python users just ignore the -O flag and run their scripts in "normal mode", which is kind of the debug mode since asserts are enabled and __debug__ is True, but is considered "production ready".

Maybe it would be wiser to switch the logic, i.e., "optimize" by default and only enable asserts in an explicit debug mode(*), but I guess this would confuse a lot of users and I doubt we will ever see such a change.

((*) This is for example how the Java VM does it, by featuring a -ea (enable assertions) switch.)

Nayuki
  • 17,911
  • 6
  • 53
  • 80
Ferdinand Beyer
  • 64,979
  • 15
  • 154
  • 145
  • 1
    Bit late now but, this answer makes no sense: it suggests assert is _not_ largely used because it is _not_ removed because people generally don't have them removed by _optimize_. Wouldn't non-removal by default result in more usage? – John Mee Dec 14 '20 at 04:31
  • 1
    My point is: Assertions are traditionally used for excessive paranoid checks, to ensure your program works during development. In production, you do not want to pay the costs for these checks (that should never fail). This is why you usually need to explicitly enable assertions in languages such as Java or C. In Python, when you use assertions excessively, you will pay the cost, as you cannot expect your users to use the "optimized" mode. – Ferdinand Beyer Jan 22 '21 at 13:55
  • Why rise of type hints among pythonistas (yes, my comment is 10y+ after accepted answer!) and static type checkers increasing usage, assert could have a greater use. (for instance as described by the great @erictraut https://github.com/microsoft/pyright/issues/4814) – comte Mar 21 '23 at 18:17
38

Several reasons come to mind...

It is not a primary function

Many programmers, lets not get bogged down by the rationale, disrespect anything which is not a direct participant in the program's penultimate functionality. The assert statement is intended for debugging and testing, and so, a luxury they can ill-afford.

Unit Testing

The assert statement predates the rise and rise of unit-testing. Whilst the assert statement still has its uses, unit-testing is now widely used for constructing a hostile environment with which to bash the crap out of a subroutine and its system. Under these conditions assert statements start to feel like knives in a gunfight.

Improved industry respect for testing

The assert statement serves best as the last line of defence. It rose to lofty and untouchable heights under the C language, when that language ruled the world, as a great way to implement the new-fangled "defensive programming"; it recognises and traps catastrophic disasters in the moment they teeter on the brink. This was before the value of Testing became widely recognised and respected and disasters were substantially more common.

Today, it is unheard of, for any serious commercial software to be released without some form of testing. Testing is taken seriously and has evolved into a massive field. There are Testing professionals and Quality Assurance departments with big checklists and formal sign-offs. Under these conditions programmers tend not to bother with asserts because they have confidence that their code will be subjected to so much tiresome testing that the odds of wacky brink-of-disaster conditions are so remote as to be negligible. That's not to say they're right, but if the blame for lazy programming can be shifted to the QA department, hell why not?

dss539
  • 6,804
  • 2
  • 34
  • 64
John Mee
  • 50,179
  • 34
  • 152
  • 186
14

I'm not an author of any of those projects, so this is just a guess based on my own experiences. Without directly asking people in those projects you won't get a concrete answer.

Assert is great when you're trying to do debugging, etc in your own application. As stated in the link you provided, however, using a conditional is better when the application might be able to predict and recover from a state. I haven't used zope, but in both Twisted and Django, their applications are able to recover and continue from many errors in your code. In a sense, they have already 'compiled away' the assertions since they actually can handle them.

Another reason, related to that, is that often applications using external libraries such as those you listed might want to do error handling. If the library simply uses assertions, no matter what the error is it will raise an AssertionError. With a conditional, the libraries can actually throw useful errors that can be caught and handled by your application.

Michael Pratt
  • 3,438
  • 1
  • 17
  • 31
  • 3
    I just mentioned those projects because they are *very* representative on python community and is supposed that contains good practices of python coding. I'm not trying to understand why they don't use asserts statement but *why asserts statement is not largely used in python community*. – Carlo Pires Feb 02 '12 at 12:13
  • 1
    That is a general reason why asserts are not used in production projects: Because they don't return a useful, handleable error message. – Michael Pratt Feb 02 '12 at 15:26
  • 7
    @Urthen: You can actually control the error message: `assert foo == 42, "foo must be 42!"`. – Ferdinand Beyer Feb 03 '12 at 16:23
0

As per my experience, asserts are majorly used in development phase of a program-to check the user defined inputs. asserts are not really needed to catch programming errors. Python itself is very well capable of trapping genuine programming errors like ZeroDivisionError, TypeError or so.

NGB
  • 400
  • 3
  • 16
  • 3
    `assert`s are still useful when it comes to checking data structure coherency, code contract compliance checking, invariant assertions, et cetera. – minmaxavg Jan 11 '18 at 13:03
0

assert is not used as it takes more time for the code to run that is we have to compromise speed