pythonsumkeyword-argumentpositional-argument

Does Python 3.6 sum() have `start=0` keyword argument?


It seems pretty basic, but as it relates to python language per se, I feel lost here. According to Python 3.6 documentation :

>>>help(sum)

...
sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers 
...

When I call: sum([0,1,2], start=1), I am getting:

TypeError: sum() takes no keyword arguments

What's going on here?


Solution

  • The / in the prototype is a convention that means that all arguments prior to it are positional only; they can't be passed by keyword. Functions defined in Python can't do this (at least, not without just accepting arguments into *args and manually unpacking the contents, though the linked PEP proposes doing allowing the syntax for Python level functions too), but since sum is a built-in implemented in C it can do this (it's actually doing the manual unpacking internally, but can advertise a more useful prototype), and define a default value much more easily. Not accepting arguments by keyword allows it to operate somewhat more efficiently than allowing for the possibility of keyword arguments.

    Point is, the argument isn't really named start, so you can't pass it by name; you have to pass it positionally, e.g.:

    sum([0,1,2], 1)