Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: is it possible to require that arguments to the functions are all keyword?

To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that?

like image 539
max Avatar asked Oct 02 '11 05:10

max


2 Answers

Only Python 3 can do it properly (and you used the python3 tag, so it's fine):

def function(*, x, y, z):
    print(x,y,z)

using **kwargs will let the user input any argument unless you check later. Also, it will hide the real arguments names from introspection.

**kwargs is not the answer for this problem.

Testing the program:

>>> function(1,2,3)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    function(1,2,3)
TypeError: function() takes exactly 0 positional arguments (3 given)
>>> function(x=1, y=2, z=3)
1 2 3
like image 144
JBernardo Avatar answered Oct 13 '22 23:10

JBernardo


You could define a decorator that, using introspection, causes an error if the function that it decorates uses any positional arguments. This allows you to prevent the use of positional arguments with some functions, while allowing you to define those functions as you wish.

As an example:

def kwargs_only(f):
    def new_f(**kwargs):
        return f(**kwargs)
    return new_f

To use it:

@kwargs_only
def abc(a, b, c): return a + b + c

You cannot use it thus (type error):

abc(1,2,3)

You can use it thus:

abc(a=1,b=2,c=3)

A more robust solution would use the decorator module.

Disclaimer: late night answers are not guaranteed!

like image 22
Zach Snow Avatar answered Oct 14 '22 01:10

Zach Snow