Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python accepts keyword arguments in CPython functions?

I use python3.3 and just found out that it accepts keyword arguments in some of its CPython functions:

>>> "I like python!".split(maxsplit=1)
['I', 'like python!']

But some other functions don't accept keyword arguments:

>>> sum([1,2,3,4], start = 10)
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    sum([1,2,3,4], start = 10)
TypeError: sum() takes no keyword arguments

My question is: what is the difference between those functions? Which functions in CPython accept keyword arguments, which functions don't? And of course - why?

like image 207
slallum Avatar asked Nov 04 '12 08:11

slallum


People also ask

Does Python support keyword arguments in functions?

So unlike many other programming languages, Python knows the names of the arguments our function accepts. That can come in handy, but with the particular function we've written here it's most clear to use all positional arguments or all keyword arguments.

How do you pass keyword arguments in Python?

In Python, we can pass a variable number of arguments to a function using special symbols. There are two special symbols: *args (Non Keyword Arguments) **kwargs (Keyword Arguments)

What are keyword arguments in Python function?

Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword. A. A.

Which function doesn't accept any argument in Python?

Which of the following functions does not accept any arguments? Explanation: The functions fillcolor(), goto() and setheading() accept arguments, whereas the function position() does not accept any arguments.


1 Answers

CPython functions that use PyArg_ParseTuple() to parse their arguments do not support keyword arguments (mostly because PyArg_ParseTuple() only supports positional parameters, e.g. a simple sequence).

This is explained in the CPython implementation details here:

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use PyArg_ParseTuple() to parse their arguments.

like image 142
Frédéric Hamidi Avatar answered Sep 21 '22 13:09

Frédéric Hamidi