Skip to content

Instantly share code, notes, and snippets.

@rctay
Created February 23, 2011 13:37
Show Gist options
  • Save rctay/840437 to your computer and use it in GitHub Desktop.
Save rctay/840437 to your computer and use it in GitHub Desktop.
[python] overloadable decorators
def decorates(dec):
def handler(*args, **kwargs):
if len(args) == 1 and callable(args[0]):
func = args[0]
return dec(func)
else:
def wrapper(func):
return dec(func, *args, **kwargs)
return wrapper
return handler
>>> from functools import wraps
>>> @decorates
... def foo(func, test=False):
... @wraps(func)
... def new_func(*args, **kwargs):
... print "got test=%s" % test
... return func(*args, **kwargs)
... return new_func
...
>>> @foo
... def foo2(x):
... return x+2
...
>>> @foo(test=True)
... def foo3(x):
... return x+3
...
>>> foo2.__name__
'foo2'
>>> foo2(1)
got test=False
3
>>> foo3.__name__
'foo3'
>>> foo3(1)
got test=True
4
@ejamesc
Copy link

ejamesc commented Feb 23, 2011

It's amazing how much one can learn from just reading your code. :) Thanks - learnt something new about Python today.

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