Created
May 28, 2011 09:30
-
-
Save piranha/996744 to your computer and use it in GitHub Desktop.
Mixin vs class decorator
This file contains hidden or 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
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()") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hehe, PyPy is wonderful, but closure is still faster than inheritance. Nice to know. :)