views:

353

answers:

2

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?

A: 

You might want to play around with the inspect module. It will let you enumerate superclasses, argument lists, and other fun stuff. It seems that you might want to inspect the argument list of the superclass __init__ method and compare it against what you have in the subclass. I'm not sure if this is going to work for you or not.

I would be careful about what assumptions you make though. It might not be safe to assume that just because class A has N arguments to __init__, subclasses will contain at least N arguments and pass the first N through to the super class. If the subclass is more specific, then it might fill in all by 2 of the arguments to its superclasses __init__ method.

D.Shawley
+1  A: 

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.

joeforker