Search code examples
pythoncompositepylint

Python composite pattern exception handling & pylint


I'm implementig a Composite pattern in this way:

1) the "abstract" component is:

class Component(object):
    """Basic Component Abstraction"""
    def __init__(self, *args, **kw):
        raise NotImplementedError("must be subclassed")

    def status(self):
        """Base Abstract method"""
        raise NotImplementedError("must be implemented")

2) a leaf:

class Leaf(Component):
    """Basic atomic component
    """
    def __init__(self, *args, **kw):
        self.dict = {}

    def status(self):
        """Retrieves properties
        """
        return self.dict

The Problem is that pylint generates, of course, this warning:

Leaf.__init__: __init__ method from base class 'Component' is not called

but into my Leaf i cannot call for:

def __init__(self, *args, **kw):
    Component.__init__(self, *args, **kw)
    self.dict = {}

without raise of the exception.

Must I ignore pylint warning or there is some bad coding?


Solution

  • Abstract initializers are a bad idea. Your code might evolve so that you want to do some initialization in the root component. And even if you don't why require the implementation of the initializer. For some subclasses an empty initializer would be an acceptable choice.

    If you don't want any instances of the Component class around, check for that in the initializer:

    class Component(object):
        def __init__(self, **kwargs):
            assert type(self) != Component, "Component must not be instantiated directly"
    
    class Leaf(Component):
        def __init__(self, some, args, **kwargs):
            # regular initialization
            Component.__init__(self, **kwargs)