2017-08-04 112 views
0

我想檢查一個Python函數是否被修飾,並將修飾器參數存儲在函數dict中。這是我的代碼:檢查一個Python函數是否用特定的修飾器裝飾

from functools import wraps 

def applies_to(segment="all"): 
    def applies(func): 
     @wraps(func) 
     def wrapper(*args, **kwargs): 
      func.func_dict["segment"] = segment 
      print func.__name__ 
      print func.func_dict 
      return func(*args, **kwargs) 
     return wrapper 
    return applies 

但看起來像字典丟失:

@applies_to(segment="mysegment") 
def foo(): 
    print "Some function" 


> foo() # --> Ok, I get the expected result 
foo 
{'segment': 'mysegment'} 

> foo.__dict__ # --> Here I get empty result. Why is the dict empty? 
{} 
+0

您在錯誤的時間修改錯誤的功能。 – user2357112

+0

我應該在運行時修改「應用」功能嗎? – jorgeas80

回答

1

好,感謝user2357112的線索,我找到了答案。即使有改善

from functools import wraps 

def applies_to(*segments): 
    def applies(func): 
     func.func_dict["segments"] = list(segments) 
     @wraps(func) 
     def wrapper(*args, **kwargs): 
      return func(*args, **kwargs) 
     return wrapper 
    return applies 

謝謝!