[Python-ideas] Boolean parameters guidelines
Chris Angelico
rosuav at gmail.com
Sat May 7 22:27:18 EDT 2016
On Sun, May 8, 2016 at 11:59 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.
The difference with open() is that it's really a flag on the resulting
file. It doesn't do something fundamentally different - it gives back
a file object either way, and there's a hidden bit of state that says
"hey, closefd was/wasn't set". There's actually a more fundamental
difference between open(fn, "rb") and open(fn, "rt"), but for
hysterical reasons that's all bound up in the "mode". IMO that would
be better done with separate keyword arguments. (Obviously I'm not
suggesting changing the existing function, but this is for PEP 8 and
general advice.)
> 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.
#2 is particularly applicable if there's a whole matrix of possible
options. Taking open() again, we have flag options for closefd,
newline, read/write/append/update, and text/binary (these last two
being packaged up into the "mode"); and more flags could easily be
created in the future, same as closefd was. Creating separate
functions for every combination would be ridiculously impractical,
ergo the one master function is the cleaner way to do it.
ChrisA
More information about the Python-ideas
mailing list