[Python-ideas] Boolean parameters guidelines

Steven D'Aprano steve at pearwood.info
Sat May 7 21:59:33 EDT 2016

On Sun, May 08, 2016 at 12:41:45AM +0300, Serhiy Storchaka wrote:
> I propose to add following recommendations in PEP 8 or other documents:
> 1. It is preferable to pass boolean arguments as keyword arguments (if 
> this is not the only argument).
> 2. It is preferable to declare boolean parameters as keyword-only 
> parameters.
> What are you think about this?

I think it is preferable *not* to have boolean parameters at all.

I don't remember if this is Guido's name for it, but I remember him 
expressing the guideline "No constant bool arguments". If you have an 
argument which takes a bool, and is used solely to switch between two 
different modes, and the caller will most likely call the function with 
the argument as a constant known when writing the code (rather than 
taking an expression or variable with value not known until runtime), 
then it is usually better to split the function into two, one for 
each mode.

For example, in the statistics module, I could have written:

def variance(data, pop=False):

and have the `pop` argument switch between population variance and 
sample variance (the default). But that would fail the "No constant bool 
args" test, since you almost always know ahead of time which variance 
you want. So instead there are two separate functions, variance and 

Obviously this is a guideline, not a hard rule, like all rules in PEP 
8, and there may be exceptions, e.g. the closefd argument to open.

So I think that if you are going to write a recommendation for treatment 
of bool arguments, it should start with "(1) Try to avoid bool args", 
explain the "No constant bool arguments" principle, and only then go on 
with "(2) if you still have bool arguments, then use keyword 
arguments..." as you suggest above.


More information about the Python-ideas mailing list