Generic constructors and duplication of internal Python logic

John J. Lee jjl at pobox.com
Wed Apr 14 18:41:33 EDT 2004


This is one of those things that I can't quite believe I've never
needed to do before.

I've got a set classes, each of which has a set of attributes that all
behave very similarly.  So, I have a class attribute (Blah.attr_spec
below), which is used by a mixin class to implement various methods
that would otherwise be highly repetitious across these classes.  I'd
like to do the same for the constructor, to avoid this kind of
nonsense:

class Blah(NamesMixin):
    attr_spec = ["foo", "bar", "baz",
                 ("optional1", None), ("optional2", None)]
    def __init__(self, foo, bar, baz,
                 optional1=None, optional2=None):
        self.foo, self.bar, self.baz = \
                   foo, bar, baz
        self.optional1, self.optional2 = \
                        optional1, optional2

So, I wrote a mixin class whose __init__ looks at the attr_spec
attribute, and uses args and kwds (below) to assign attributes in the
same sort of way as the special-case code above:

class ArgsMixin:
    def __init__(self, *args, **kwds):
        # set attributes based on arguments passed in, as done
        # manually in Blah.__init__, above
        ... lots of logic already present in Python goes here...

That immediately leads to duplication of Python's internal logic: I
have to check things like:

 -are there too many positional arguments?
 -any unexpected keyword arguments?
 -multiple keyword arguments?
 -any duplication between positional and keyword arguments?

etc.

Surely there's some easy way of making use of Python's internal logic
here?  For some reason, I can't see how.  Can anybody see a way?


John



More information about the Python-list mailing list