Question

Specify None as default value for Boolean function argument?

The prototype for numpy.histogram contains an input argument density of type bool and default value None. If the caller does not supply density, what value does it take on?

The closest Q&A that I can find is this. The first answer says "Don't use False as a value for a non-bool field", which doesn't apply here. It also says that bool(x) returns False, but that doesn't assure the caller that the function will set density to False if it isn't provided. Is this a mistake in the documentation of the prototype for numpy.histogram, or am I missing something about the documentation convention?

The other answers to the above Q&A do not seem relevant to my question.

 3  56  3
1 Jan 1970

Solution

 2

From the method's source code, we can see that the density argument is only used at the end of the method in an if statement.

In Python, None is interpreted as False (is is a falsy value). This means that providing None to numpy.histogram's density argument is equivalent to providing it with False.

I suppose that the developers found it more appropriate to use None instead of False for a value that has not been defined by the user.

2024-07-08
TrickyTroll

Solution

 1

This is at best poorly documented. The documentation seems to imply that False and the default None will be treated equivalently, but it should either document that explicitly, or use the more sensible False as the default value. (The third option would be if the function makes a distinction between False and None, but that also should be explicitly documented.)

2024-07-08
chepner