我已经写了一个装饰器,用于确保传递给构造函数的关键字参数是正确/预期的。以下是代码:
from functools import wraps
def keyargs_check(keywords):
"""
This decorator ensures that the keys passed in kwargs are the onces that
are specified in the passed tuple. When applied this decorate will
check the keywords and will throw an exception if the developer used
one that is not recognized.
@type keywords: tuple
@param keywords: A tuple with all the keywords recognized by the function.
"""
def wrap(f):
@wraps(f)
def newFunction(*args, **kw):
# we are going to add an extra check in kw
for current_key in kw.keys():
if not current_key in keywords:
raise ValueError(
"The key {0} is a not recognized parameters by {1}.".format(
current_key, f.__name__))
return f(*args, **kw)
return newFunction
return wrap
这个修饰器的一个例子如下:
class Person(object):
@keyargs_check(("name", "surname", "age"))
def __init__(self, **kwargs):
# perform init according to args
使用上述代码,如果开发者传递了一个名为“blah”的关键字参数,它将会抛出一个异常。不幸的是,我的实现在继承方面存在一个重大问题,如果我定义以下内容:
class PersonTest(Person):
@keyargs_check(("test"))
def __init__(self, **kwargs):
Person.__init__(self,**kwargs)
因为我将kwargs传递给超类init方法,所以我会得到一个异常,因为“test”不在传递给超类装饰器的元组中。有没有办法让超类中使用的装饰器知道额外的关键字?或者更好的是,有没有标准的方法来实现我想要的?更新:我更感兴趣的是自动化地抛出异常的方式,当开发人员传递错误的kwarg时,而不是我使用kwargs而不是args的事实。我的意思是,我不想在每个类中编写检查传递给方法的参数的代码。