Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot use keyword argument on range function?

Tags:

python

In the python documenation, it says:

Any function argument, no matter non-optional or optional (with default value) can be called as keyword argument as long as one of the argument names matches. Keyword argument, however, must follow all positional arguments.

I tried this out:

kwargs = {'step':-1, 'start':10, 'stop':5}
list(range(**kwargs))

But python gives men an error:

TypeError: range() takes no keyword arguments

Why is this?

like image 984
Gary Avatar asked Mar 08 '15 12:03

Gary


2 Answers

range() is not a python function. It is a C type; C types follow different rules for arguments and range() only accepts positional arguments.

See the Calls expressions documentation:

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.

The positional parameters of range() are not named so cannot be used as keyword arguments.

like image 140
Martijn Pieters Avatar answered Sep 24 '22 19:09

Martijn Pieters


As you know by now the real answer is that range is a C function which for some reason does not have the same rules of python (would be nice to know why).

But you can do this instead:

range(*{'start':0,'stop':10,'step':2}.values())

like image 41
Charlie Parker Avatar answered Sep 21 '22 19:09

Charlie Parker