[OT-ish] Design principles: no bool arguments

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Aug 25 03:13:07 EDT 2011

One design principle often mentioned here (with a certain degree of
disagreement[1]) is the idea that as a general rule, you shouldn't write
functions that take a bool argument to switch between two slightly
different behaviours.

This is a principle often championed by the BDFL, Guido van Rossum.

Here's a Javascript-centric article which discusses the same idea, and gives
it a name: the Boolean Trap.


No doubt there are counter arguments as well. The most obvious to me is if
the flag=True and flag=False functions share a lot of code, it is poor
practice to implement them as two functions with two copies of almost
identical code.

My solution to this is a technical violation of the "Avoid Boolean Trap"
principle, but only in a private function:

def spam_on(arg):
     _spam(arg, True)

def spam_off(arg):
     _spam(arg, False)

def _spam(arg, flag):
    do stuff
    if flag:
    more stuff

[1] This is the Internet. There's *always* a certain amount of disagreement.


More information about the Python-list mailing list