【发布时间】:2009-09-18 20:01:57
【问题描述】:
我做了一个装饰器,用来确保传递给构造函数的关键字参数是正确/预期的。代码如下:
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 的事实。我的意思是,我不想编写代码来检查每个类中传递给方法的参数。
【问题讨论】:
标签: python