Skip to content

Instantly share code, notes, and snippets.

@xfire
Created May 14, 2009 21:07
Show Gist options
  • Save xfire/111923 to your computer and use it in GitHub Desktop.
Save xfire/111923 to your computer and use it in GitHub Desktop.
python decorator example
#!/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)
print
@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