The Python Oracle

Why would mock be adding __nonzero__ method calls?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
01:06 Accepted answer (Score 23)
02:29 Thank you

--

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

Question links:
[mock]: http://pypi.python.org/pypi/mock

--

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

--

Tags
#python #unittesting #mocking

#avk47



ACCEPTED ANSWER

Score 23


Short answer:

If your mocked function does not have an explicit return_value or side_effect that returns, you will see this as Python attempts to evaluate the truthiness of your mock. Ensure your mock has one.

Either initialise it with one:

item = MagicMock(return_value=True)

or add one in:

item.return_value = True

Explanation:

When you do if not x:, you are probably thinking if x is False.

Python doesn't actually do this - it does if bool(x) is False (this is Python's truthiness concept - that values evaluate to True or False), and bool(x) is actually a call to x.__nonzero__() (or x.__bool__() in 3.x).

This is to provide Python's nice if behaviour - when you do if []:, a lot of languages would treat any object as True, but Python is designed to make code readable, so it delegates and a list's __nonzero__() method will return False if it is empty. This allows for more code that reads more naturally, and explains why you will see these calls.