Skip to content

Instantly share code, notes, and snippets.

@josh-howes
Last active November 13, 2015 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josh-howes/0c3f18db7853f01f4dc1 to your computer and use it in GitHub Desktop.
Save josh-howes/0c3f18db7853f01f4dc1 to your computer and use it in GitHub Desktop.
Add Decorating of Abstract Class Methods
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