问题
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?
回答1:
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
回答2:
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!
回答3:
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")
来源:https://stackoverflow.com/questions/7624840/python-is-it-possible-to-require-that-arguments-to-the-functions-are-all-keywor