2

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?

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
Dima Lituiev
  • 10,690
  • 7
  • 32
  • 47

1 Answers1

7

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)
ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
  • 1
    interesting. Is there a documentation about the `/` thing? – Dima Lituiev Dec 21 '18 at 00:06
  • @DimaLituiev: No *good* documentation I can find, but it's mentioned [under item #10 in the Argument Clinic docs on converting your first function](https://docs.python.org/3/howto/clinic.html?highlight=positional-only#converting-your-first-function). The Argument Clinic is an initiative to simplify documenting and parsing function arguments for C level built-ins. – ShadowRanger Dec 21 '18 at 00:14
  • There is [an open bug to document them](https://bugs.python.org/issue21314), and it's also mentioned in [PEP 570](https://www.python.org/dev/peps/pep-0570/). – ShadowRanger Dec 21 '18 at 00:15