Skip to content

Instantly share code, notes, and snippets.

@frruit
Created March 3, 2017 07:00
Show Gist options
  • Save frruit/27c5222c762de86c8bdd6d6891b3d333 to your computer and use it in GitHub Desktop.
Save frruit/27c5222c762de86c8bdd6d6891b3d333 to your computer and use it in GitHub Desktop.
My solution how to handle data collection from different tools is to implement an ABC Class end reduce copy past of code in the childs by implementing a decorator with pre an post handling
from abc import ABCMeta, abstractmethod
def prepost(f):
def prepost_wrapper(self, *args, **kwargs):
print('prepost wrapper')
pre_name = 'pre_' + f.__name__
post_name = 'post_' + f.__name__
if hasattr(self, pre_name):
getattr(self, pre_name)(*args, **kwargs)
ret = f(self, *args, **kwargs)
if hasattr(self, post_name):
getattr(self, post_name)(*args, **kwargs)
return ret
return prepost_wrapper
class Collector(metaclass=ABCMeta):
@abstractmethod
def __init__(self, *args, **kwargs):
pass
@abstractmethod
def load(self, *args, **kwargs):
pass
@abstractmethod
def save(self, *args, **kwargs):
pass
@abstractmethod
def get_latest_data(self, *args, **kwargs):
pass
@abstractmethod
def get_complete_history(self, *args, **kwargs):
pass
def pre_get_latest_data(self, *args, **kwargs):
print('pre_get_complete_data_history')
def post_get_latest_data(self, *args, **kwargs):
print('post_get_complete_data_history')
class TestMetrics(Collector):
def __init__(self, *args, **kwargs):
pass
def load(self, *args, **kwargs):
pass
def save(self, *args, **kwargs):
pass
@prepost
def get_latest_data(self, *args, **kwargs):
print('get latest data')
def get_complete_history(self, *args, **kwargs):
pass
class WarningPluginMetrics(Collector):
def __init__(self, *args, **kwargs):
pass
def share(self, *args, **kwargs):
pass
tm = TestMetrics()
tm.get_latest_data()
@frruit
Copy link
Author

frruit commented Mar 3, 2017

The output of this code is

>>> prepost wrapper
>>> pre_get_complete_data_history
>>> get latest data
>>> post_get_complete_data_history

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment