I made a decorator that I used to ensure that the keyword arguments passed to the constructor are correct / expected . The code is as follows:
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):
code> An example of using this decorator will be as follows:
class Person(object): @keyargs_check(("name", "surname", "age")) def __init__(self, **kwargs):
code> Using the code above, if a developer passes key arguments like "blah", it will throw an exception . Unfortunately, my implementation has a serious inheritance problem if I define the following:
class PersonTest(Person): @keyargs_check(("test")) def __init__(self, **kwargs): Person.__init__(self,**kwargs)
code>
Since I am passing kwargs to the init method of the super class, I am going to get an exception because "test" is not in the tuple passed to the superclass decorator. Is there a way to let the decorator used in the superclass learn about additional keywords? or the event is better, is there a standard way to achieve what I want?
Update: I'm more interested in automating how I throw an exception when a developer passes the wrong kwarg, rather than the fact that I use kwargs instead of args. I mean, I donβt want to write code that checks the arguments passed to the method in each class.
python
mandel Sep 18 '09 at 20:01 2009-09-18 20:01
source share