Created
May 14, 2009 21:07
-
-
Save xfire/111923 to your computer and use it in GitHub Desktop.
python decorator example
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
#!/usr/bin/env python | |
# | |
# vim:syntax=python:sw=4:ts=4:expandtab | |
import functools | |
def wrap(orig_func): | |
# now some funky python magic | |
@functools.wraps(orig_func) | |
def outer(new_func): | |
def wrapper(*args, **kwargs): | |
return new_func(orig_func, *args, **kwargs) | |
setattr(orig_func.im_class, orig_func.__name__, wrapper) | |
return wrapper | |
return outer | |
class Foo(object): | |
def __init__(self, bar): | |
self.bar = bar | |
def foo(self, arg): | |
print 'Foo.foo()', self.bar, arg | |
Foo(23).foo(42) | |
@wrap(Foo.foo) | |
def new_foo(forig, self, arg): | |
print '-> enter new_foo', arg | |
forig(self, arg * 100) | |
print '<- leave new_foo' | |
Foo(23).foo(42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment