Restrict internal use method call
Let's say I have a class Task
and another class Subtask
that is delegated to perform a specific task, but always in the execution context Task
. This means it Subtask
always accepts Task
and performs actions on attributes Tasks
:
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 does a specific update. This method is intended to be used for internal use only:
class Task:
def _update(self):
# do something restricted
But then we really want to call this method from within Subtask
to perform these updates:
class Subtask:
def run(self):
# do stuff
self.task._update()
Here's the problem: this is wrong behavior. The internal use method should not be called from any other context and the IDE gives the appropriate warning as expected.
However, I do not want this method to be publicly available Task.update()
because it is still of limited use. We just want to do something like friendship like in C ++.
We want to keep this method Task._update()
private, but we give the class a Subclass
special permission.
Is there a way to do this?
PS: I know how Python works, I know I can just use this method externally and ignore this warning or make it public and just not use it elsewhere to summarize: be responsible , as the Python motto proclaims. I agree with this, but I also wonder if there is any way to achieve what I need in a way that makes sense with Python philosophy.
source to share
I believe most Pythonic solutions will use private variables as they are available anywhere if you explicitly.
class Task:
def __update(self): # Two underscores for private
# do something restricted
class Subtask:
def __init__(self, task):
self.task = task
def run(self):
# Do stuff
self.task._Task__update() # Access private method
source to share