On 8/25/2011 3:13 AM, Steven D'Aprano wrote:
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.

You missed the essential caveat to his rule. See below.

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

http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html

This was mostly about defining parameters as positional-only (which Python does not have) versus keyword-optional or keyword only. In Python, callers always have the 'keyword = BOOL' option.

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:
         a
     else:
         b
     more stuff

As I think one of the comments pointed out, this now means that if I the user need to compute whether to turn off or on, I now have to write

if expr: spam_on(arg)
elses: spam_off(arg)

(or put this on 4 lines if you prefer ;-) instead of

spam_switch(expr, arg)

so moving the conditional out of the function *pushes it onto every user*. Note that naming the function 'switch' and putting the bool as the first param makes it pretty obvious that True=='on', and False=='off'.

As I remember, Guido only recommendeds splitting if the boolean arg is (would be) always (nearly) passed as a constant True or False. Of course, I am not sure how one forsees that at the design stage, prior to field use.

--
Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to