Last active
November 13, 2015 22:45
-
-
Save josh-howes/0c3f18db7853f01f4dc1 to your computer and use it in GitHub Desktop.
Add Decorating of Abstract Class Methods
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
from abc import ABCMeta, abstractmethod | |
import types | |
import time | |
from functools import wraps | |
def with_timing(f): | |
@wraps(f) | |
def wrapper(*args, **kwds): | |
time_start = time.time() | |
result = f(*args, **kwds) | |
time_end = time.time() | |
print ('func:%r args:[%r, %r] took: %2.4f sec' % (f.__name__, args, kwds, time_end-time_start)) | |
return result | |
return wrapper | |
class TimingMeta(ABCMeta): | |
"""Metaclass for adding post-hoc support for timing class methods.""" | |
def __new__(mcs, name, bases, attrs): | |
for attr_name, attr_value in attrs.iteritems(): | |
if isinstance(attr_value, types.FunctionType): | |
if attr_name != '__init__': | |
attrs[attr_name] = with_timing((attr_value)) | |
return super(TimingMeta, mcs).__new__(mcs, name, bases, attrs) | |
# Example Usage | |
class TimedMethodClass(object): | |
__metaclass__ = ABCMeta | |
@abstractmethod | |
def say_hello(self): | |
pass | |
class MyConcrete(TimedMethodClass): | |
__metaclass__ = TimingMeta | |
def say_hello(self): | |
print("Hello World") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment