Skip to content

Instantly share code, notes, and snippets.

@safhac
Last active April 27, 2022 09:38
Show Gist options
  • Save safhac/7ea66b7b13bc4d3184a707774ad2c8a1 to your computer and use it in GitHub Desktop.
Save safhac/7ea66b7b13bc4d3184a707774ad2c8a1 to your computer and use it in GitHub Desktop.
create a safe abstract worker
"""
class BaseWorker:
def __int__(self):
self.counter = 0
def work(self):
self.counter += 1
def get_counter(self):
return self.counter
# fix the base worker so implementations can be trusted.
"""
class BaseWorker(ABC):
def __init__(self):
self._counter = 0
def __getattribute__(self, item):
if item == 'work':
self._BaseWorker__do_work()
return super().__getattribute__(item)
@property
def counter(self):
return self._counter
def __do_work(self):
caller = inspect.stack()[1][3]
if not '__getattribute__' in caller:
warnings.warn("built in descriptor, no need to explicitly call worker()")
return
self._counter += 1
@abstractmethod
def work(self):
print('calling work')
return self.__do_work()
def get_counter(self):
return self._counter
class MyWorker(BaseWorker):
def work(self):
super(MyWorker, self).work()
print("hello")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment