Skip to content

Instantly share code, notes, and snippets.

@piranha
Created May 28, 2011 09:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piranha/996744 to your computer and use it in GitHub Desktop.
Save piranha/996744 to your computer and use it in GitHub Desktop.
Mixin vs class decorator
import logging, timeit
class LoggedSetItemMixin(object):
def __setitem__(self, index, value):
logging.info('Setting %r to %r' % (index, value))
super(LoggedSetItemMixin, self).__setitem__(index,value)
class LoggingDict(LoggedSetItemMixin, dict):
pass
class LoggingList(LoggedSetItemMixin, list):
pass
def LoggedSetItem(cls):
orig_setitem = cls.__setitem__
def __setitem__(self, index, value):
logging.info('Setting %r to %r' % (index, value))
return orig_setitem(self, index, value)
cls.__setitem__ = __setitem__
return cls
@LoggedSetItem
class DecLoggingDict(dict):
pass
@LoggedSetItem
class DecLoggingList(list):
pass
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
dl = LoggingDict()
dl['a'] = 1
dd = DecLoggingDict()
dd['a'] = 2
logging.getLogger().setLevel(logging.ERROR)
# 8.46709299088
print timeit.timeit("d['a'] = 1",
"from __main__ import LoggingDict\n"
"d = LoggingDict()")
# 7.8665599823
print timeit.timeit("d['a'] = 1",
"from __main__ import DecLoggingDict\n"
"d = DecLoggingDict()")
@asenchi
Copy link

asenchi commented May 28, 2011

I thought this was an interesting stat:

:: shavazooki ~
:: % python2.7 tmp/class-deco.py
INFO:root:Setting 'a' to 1
INFO:root:Setting 'a' to 2
2.8918337822
2.66344285011
:: shavazooki ~
:: % pypy tmp/class-deco.py
INFO:root:Setting 'a' to 1
INFO:root:Setting 'a' to 2
0.367079019547
0.348106861115

@piranha
Copy link
Author

piranha commented May 28, 2011

Hehe, PyPy is wonderful, but closure is still faster than inheritance. Nice to know. :)

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