python: is it possible to require that arguments to the functions are all keyword?
To avoid the obvious bugs, I'd lik开发者_如何学Goe to prevent the use of positional arguments with some functions. Is there any way to achieve that?
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
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!
Yes, just use the **kwargs
construct and only read your parameters from there.
def my_function(**kwargs):
for key, value in kwargs.iteritems():
print ("%s = %s" % (key, value))
my_function(a="test", b="string")
精彩评论