pythonpython-typingpython-decorators

Validating Python Arguments in Subclasses


I'm trying to validate a few python arguments. Until we get the new static typing in Python 3.0, what is the best way of going about this.

Here is an example of what I am attempting:

class A(object):
    @accepts(int, int, int)
    def __init__(a, b, c):
        pass

class B(A):
    @accepts(int, int, int, int)
    def __init__(a, b, c, d):
        A.__init__(a, b, c)

As you can see the decorator is nicely performing type checking of the inputs to my class, but I have to define all the arguments to the second class, which gets very nasty when I have multiple levels of inheritance. I can use kwargs with some success, but it's not quite as nice as the above approach for type checking.

Essentially I want to pop one argument off the kwargs list and check it's type, then pass the remainder to it's parent, but do this in a very flexible and clean way as this scales.

Any suggestions?


Solution

  • Why not just define an any value, and decorate the subclass constructor with @accepts(any, any, any, int)? Your decorator won't check parameters marked with any, and the @accepts on the superclass constructor will check all the arguments passed up to it by subclasses.