[Python-ideas] Make all builtin functions accept None for optional arguments

Terry Reedy tjreedy at udel.edu
Wed Feb 5 03:17:54 CET 2014


On 2/4/2014 5:45 AM, Ram Rachum wrote:
> Here is something that always annoys me.
>
> I was going to write my own rreplace function, like this:
>
>     def rreplace(s, old, new, count=None):
>          return new.join(s.rsplit(old, count))
>
>
> But lo and behold, I have to write it like this:
>
>     def rreplace(s, old, new, count=None):
>          return new.join(s.rsplit(old, count) if count is not None
>                          else s.rsplit(old))
>
>
> Why? Because the `str.rsplit` can't handle a count of `None`. That is
> quite annoying.

As MRAB pointed out, count does have a default

 >>> help(str.rsplit)
Help on method_descriptor:

rsplit(...)
     S.rsplit(sep=None, maxsplit=-1) -> list of strings

But there are builtins with optional parameters with no default, and 
they *are* annoying because they do need conditional code like the above 
to not pass any value. Some developers would like to add None as default 
for such  cases. For reasons explained by Nick, at least some will in 3.5.

Replacing (or augmenting) -1 with None when -1 means None is trickier 
because of back compatibility.

Another annoyance for builtins is the lack of documentation as to which 
parameters can only be passed by position and not by keyword. You cannot 
be sure from just reading the above that ''.rsplit(maxsplit = 3) is even 
legal. This should also be fixed in 3.5.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list