Restrict internal usage method caller

Viewed 111

Say I have a class Task and another class Subtask to which the execution of a particular task is delegated but always in the context of a Task execution. This implies the Subtask always takes a Task, and it performs actions on the Tasks's attributes:

class Task:
    pass

class Subtask:
    def __init__(self, task):
        self.task = task

    def run(self):
        # performs actions on self.task own attributes

Then we have a method in Task that makes a specific update. This method is supposed to be used for internal use only:

class Task:
    def _update(self):
        # do something restricted

But then we actually want to call this method from the Subtask to perform those updates:

class Subtask:
    def run(self):
        # do stuff
        self.task._update()

Here is the issue: this is an irregular behavior. An internal usage only method should not be called from another context, and the IDE gives a corresponding warning as expected.

However, I do not want to make the method public, Task.update(), because it is still of restricted use. We just want to do sort of like friendship as found in C++.

We want to keep that Task._update() method private but give the Subclass class a special permission.

Is there any way to do this?

PS: I know how Python works, I know I can just use that method from outside and ignore the warning, or make it public and simply don't use it elsewhere, to summarize: be responsible, as it the motto Python proclaims. I agree with this, but I also wonder if there is any way I could achieve what I'm after in a way that makes sense with the Python philosophy.

1 Answers
Related