The assert
statement allows you to introduce “sanity checks” into a program.
assert
is a simple statement with the following syntax:
assert
condition
[,
expression
]
When you run Python with the optimize flag
(-O
, as covered in
“Command-Line Syntax and Options”),
assert
is a null
operation: the compiler generates no code for it.
Otherwise, assert
evaluates condition
.
When condition
is satisfied, assert
does nothing. When condition
is not satisfied,
assert
instantiates AssertionError
with expression
as the argument (or without arguments, if
there is no expression
) and raises the resulting
instance.2
assert
statements can be an effective way to document
your program. When you want to state that a significant, nonobvious condition
C
is known to hold at a certain point
in a program’s execution (known as an invariant of your program),
assert
C
is often better than
a comment that just states that C
holds.
The advantage of assert
is that, when C
does not in fact hold, assert
immediately alerts
you to the problem by raising AssertionError
, if the program
is running without the -O
flag. Once the
code is thoroughly debugged, run it with -O
,
turning assert
into a null operation and incurring no overhead
(the assert
remains in your source code to document the invariant).
Never use assert
for other purposes besides sanity-checking
program invariants. A serious but very common mistake is to use
assert
about the values of inputs or arguments: checking
for erroneous arguments or inputs is best done more explicitly, and
in particular must not be turned into a null operation by a command-line
flag.
When you run Python without option
-O
,
the __debug__
built-in variable is True
.
When you run Python with option -O
,
__debug__
is False
. Also, with option
-O
, the compiler generates no code for
any if
statement whose condition is __debug__
.
To exploit this optimization, surround the definitions of functions
that you call only in assert
statements with if
__debug__:
. This technique makes compiled code smaller and faster
when Python is run with -O
, and enhances
program clarity by showing that those functions exist only to perform
sanity checks.