[Python-Dev] (#19562) Asserts in Python stdlib code (datetime.py)

Jan Kaliszewski zuo at chopin.edu.pl
Mon Nov 18 03:34:50 CET 2013

17.11.2013 23:05, Guido van Rossum wrote:

> The correct rule should be "don't use assert (the statement) to check
> for valid user input" and the stated reason should be that the assert
> statement was *designed* to be disabled globally, not to be a
> shorthand for "if not X: raise (mumble) Y". A corollary should also 
> be
> that unittests should not use the assert statement; some frameworks
> sadly encourage the anti-pattern of using it in tests.

My problem with -O (and -OO) is that even though my code is valid (in 
terms of the rule 'use assert only for should-never-happen cases') I 
have no control over 3rd party library code: I can never know whether 
doesn't it break if I turn -O or -OO on (as long as I do not analyze 
carefully the code of the libraries I use, including writing regression 
tests [for 3rd party code]...).

Woudln't it to be useful to add possibility to place an "optimisation 
cookie" (syntactically analogous to "encoding cookie") at the beginning 
of each of my source files (when I know they are "-O"-safe), e.g.:

     # -*- opt: asserts -*-

or even combined with an encoding cookie:

     # -*- coding: utf-8; opt: asserts, docstrings -*-

* The -O flag would be effectively applied *only* to a file containing 
such a cookie and *exactly* according to the cookie content (whether 
asserts, whether docstrings...).
* Running without -O/-OO would mean ignoring optimisation cookies.
* The -OO flag would mean removing both asserts and docstrings (i.e. 
the status quo of -OO).
* Fine-grained explicit command line flags such as --remove-asserts and 
--remove-docstings could also be useful.

(Of course, the '-*-' fragments in the above examples are purely 
conventional; the actual regex would not include them as it does not 
include them now for encoding cookies.)


More information about the Python-Dev mailing list