Python has keyword only parameters!

Maybe I should have known this about Python by now, but…

Little did I know (was wishing for it today), but there IS a way to specify that arguments MUST be keyword only.

>>> def foo(a,b,*,c,d):
...     print(a,b,c,d)
...
>>> foo(1,2,3,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 2 positional arguments (4 given)
In this case, everything after the * is required to be keyword only. This means that you can safely amend the function definition to re-order or even add keyword arguments.
Likewise, the following requires ALL keyword arguments.
>>> def foo(*,a,b):
...     print(a,b)
...
>>> foo(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 positional arguments (2 given)

>>> foo(a=1, b=2)
1 2


Read more about it at:

http://www.python.org/dev/peps/pep-3102/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s