Fiver
Fiver

Reputation: 10167

Making an overridden abstract method in a subclass "private"

Say I have a an abstract base class, and a subclass that is also abstract:

class Daemon(object)::
    __metaclass__ = abc.ABCMeta

    def __init__(self, pid_file):
        ...

    @abc.abstractmethod
    def run(self):
        return


class Worker(Daemon):
    __metaclass__ = abc.ABCMeta

    def __init__(self):
        ...

    def run(self):
        # do stuff
        self.process()

    @abc.abstractmethod
    def process(self):
        """
        Override this method when subclassing Worker.
        """
        return

When other developers build new actual "working" Worker sub-classes, I'd like to make it clear that they shouldn't mess with the run method. If I use __run it hints that the method is private, but then I'm creating a private abstract method in Daemon, which is a bit confusing. It also seems odd to have it protected using _run because I don't want Worker sub-classes to mess with it. I realize the private and protected names are just useful conventions in Python, I just want to make it clear for others how to build new Worker sub-classes.

Is there a Pythonic convention to follow in this case? Or is this just a matter of making the documentation clear?

Upvotes: 0

Views: 448

Answers (2)

lucasg
lucasg

Reputation: 11002

You can always enforce the non-redeclared type of the method, although it's hackish : python: enforce that a class method is only called from within another class method?

Upvotes: 1

Steve Barnes
Steve Barnes

Reputation: 28370

Basically either force other coders to use pylint which will moan about the use of private members or just beat them about the head until they start to listen. BTW if you are using a decent VCS such as hg, git, svn, then you can find examples of pre-commit hooks that will run pylint against all commits and reject any that fail which may be a way of enforcing the convention and a large number of others - it will also improve the project quality by a large amount so will be well worth the effort - just don't expect to be popular.

Since you have marked the methods of private you could also vary the signatures from time to time and tell those that moan that they should be leaving them alone - pylint will probably be easier to justify though.

Upvotes: 0

Related Questions