Created
February 23, 2011 13:37
-
-
Save rctay/840437 to your computer and use it in GitHub Desktop.
[python] overloadable decorators
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
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 |
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
>>> 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's amazing how much one can learn from just reading your code. :) Thanks - learnt something new about Python today.