Question

Let us define a class called Filter. I want this class to be extended by subclasses and I want all these subclasses to override a method : job.

More specifically

class Filter(object):
    def __init__(self, csvin=None):
        self._input = csvin

    # I want this to be abstract. All the classes that inherit from Filter should
    # implement their own version of job.
    def job(self):
        pass

Said differently, I want to make sure that any subclass of Filter has a method called job.

I heard about the module abc, but I also read about these concepts called duck-typing and EAFP. My understanding is that, if I am a duck, I will just try to run

f = SomeFilter()
f.job()

and see if it works. This is my problem if it raises any exception, I should have been more careful when I wrote the class SomeFilter.

I am pretty sure I do not fully understand the meaning of duck-typing and EAFP, but if it means that I have to postpone debugging as late as possible (that is, at invokation time), then I disagree with this way of thinking. I do not understand why so many people seem to appreciate this EAFP philosophy, but I wish to be part of them.

Can someone convert me and explain how to achieve this in a safe and predictive manner, that is by preventing the programmer from making a mistake when extending Filter, in a pythonic way.

Was it helpful?

Solution

You can use raise NotImplementedError, as per the documentation:

class Filter(object):
    def __init__(self, csvin=None):
        self._input = csvin

    # I want this to be abstract. All the classes that inherit from Filter should
    # implement their own version of job.
    def job(self):
        raise NotImplementedError
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top