The Python Oracle

assert true vs assert is not None

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 Assert True Vs Assert Is Not None
00:42 Accepted Answer Score 26
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/5906...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #automatedtests

#avk47



ACCEPTED ANSWER

Score 26


tldr;

There is a functional difference in general, though in your particular case the execution result will be the same for both techniques. It now depends only on your willingness to be either explicit or concise.

Full answer

Assuming that a is a variable in Python, there is a difference between:

assert a

and

assert a is not None

In the fist case, you are evaluating the return of the call to the bool() buit-in on the object, which follows multiple strategies to get a result, as it was already discussed here.

This evaluates only according to the object's class implementation. Did you have a look on the class of your response object? It will tell you how bool(response) behaves.

In the second case, your are evaluating a as not being None. This is completely different. For example, an empty list will evaluate to False but is not None:

>>> a = []
>>> a is not None
True
>>> assert a is not None
>>> assert a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

If your response object is a sub-class derived from list, then it will probably behave the same way, so evaluating the emptiness of response is not equivalent to evaluating response as None.

In your case, I guess that your response object is provided by the request library. If so, then yes, in your particular case, both techniques are functionally equivalent, though you should notice a tiny performance gain evaluating against None.