Last active
April 27, 2022 09:38
-
-
Save safhac/7ea66b7b13bc4d3184a707774ad2c8a1 to your computer and use it in GitHub Desktop.
create a safe abstract worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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