Created
February 3, 2012 17:06
-
-
Save jldupont/1731173 to your computer and use it in GitHub Desktop.
Fun with Python 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
""" | |
Created on 2012-02-03 | |
@author: jldupont | |
@pattern(int, str, [], "p1>p2") | |
@patterned | |
def function_name(p1, p2, p3): | |
@pattern() | |
def function_name(p1, p2): | |
pass | |
@pattern() | |
def function_name(p1, p2, p3): | |
pass | |
@default | |
def function_name(p1, p2, p3): | |
pass | |
""" | |
from functools import wraps | |
def patterned(f): | |
@wraps(f) | |
def wrapper(*pa, **ka): | |
return f(*pa, **ka) | |
ps=globals().get("__PATTERNED__", {}) | |
ps[f.__name__]=[] | |
globals()['__PATTERNED__']=ps | |
return wrapper | |
class pattern(object): | |
def __init__(self, *ps): | |
self.ps=ps | |
print "__init__ / ps: ", ps | |
def __call__(self, f, *cpa): | |
print "__call__ / f: ",f | |
print "__call__/ cpa: ", cpa | |
def wrapped_f(*pa): | |
print "wrapped_f/pa: ", pa | |
return f(*pa) | |
return wrapped_f | |
@patterned | |
def f1(p1, p2): | |
pass | |
@pattern(int, int) | |
def f1_p1(p1, p2): | |
print "f1_p1: ", p1, p2 | |
print "---------------" | |
@pattern | |
def f1_p2(p1, p2): | |
print "f1_p2: ", p1, p2 | |
print "++++++++++++++++++++" | |
f1_p1(1, 2) | |
print "++++++++++++++++++++" | |
f1_p2(3, 4) | |
""" | |
__init__ / ps: (<type 'int'>, <type 'int'>) | |
__call__ / f: <function f1_p1 at 0x7f559a5192a8> | |
__call__/ cpa: () | |
--------------- | |
__init__ / ps: (<function f1_p2 at 0x7f559a519398>,) | |
++++++++++++++++++++ | |
wrapped_f/pa: (1, 2) | |
f1_p1: 1 2 | |
++++++++++++++++++++ | |
__call__ / f: 3 | |
__call__/ cpa: (4,) | |
""" | |
if __name__=="__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment