[Python-ideas] Boolean parameters guidelines

Koos Zevenhoven k7hoven at gmail.com
Tue May 10 09:43:03 EDT 2016


On Sun, May 8, 2016 at 3:14 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 8 May 2016 at 07:41, Serhiy Storchaka <storchaka at gmail.com> 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?
>
> With Steven's suggestion to also articulate the "Would two functions
> be better?" question, I think it's a good idea.
>
> Suggested points to note:
>
> 1. Do not use a boolean toggle to change the return type of a
> function, define two different functions (e.g. os.walk vs os.fwalk,
> os.getcwd vs os.getcwdb)
> 2. If the boolean toggle is expected to be constant for any given
> call-site, consider defining two different functions (e.g.
> statistics.variance vs statistics.pvariance)
> 3. If a boolean toggle is deemed appropriate, it is preferable to make
> it keyword-only so call sites are always self-documenting
> 4. When calling a function that accepts a boolean toggle, it is
> preferable to pass it by keyword to make the call more
> self-documenting
>
> The reason I think this is worth documenting is that it comes up
> regularly in PEPs that require some associated API design, and these
> are the rules of thumb we generally apply.
>

Regarding 3 and 4 above:

More generally, would it not be a good thing to always consider using
a keyword-only argument instead of a regular keyword argument
(argument with a default value)?

When using keyword-only arguments:

A. It is possible to later turn a keyword-only argument into a regular
(keyword) argument without breaking backwards compatibility of the
API.

or

B. It is possible to add optional *positional* arguments to the
function later without breaking the API.

C. If the keyword-only argument later becomes redundant, it is
possible to swallow it in **kwargs and make it effectively disappear
(well, almost).

-- Koos


> Cheers,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list