2014-03-03 144 views
1

(Python 2.7)由于装饰器不能与他们正在装饰的函数共享变量,我怎样才能使/将object_list传递给装饰函数?我有一些功能将使用raw_turn_over_mailer()装饰器,我想保留object_list到可能的地方装饰功能。函数和它的装饰器之间的Python-共享变量

def raw_turn_over_mailer(function): 
    @wraps(function) 
    def wrapper(requests): 
     original_function = function(requests) 
     if object_list: 
      .... 
     return original_function 
    return wrapper 


@raw_turn_over_mailer 
def one(requests): 
    object_list = [x for x in requests 
      if x.account_type.name == 'AccountType1'] 
@raw_turn_over_mailer 
def two(requests): 
    object_list = [x for x in requests 
      if x.account_type.name == 'AccountType2'] 

@periodic_task(run_every=crontab(hour="*", minute="*", day_of_week="*")) 
def turn_over_mailer(): 
    HOURS = 1000 
    requests = Request.objects.filter(completed=False, date_due__gte=hours_ahead(0), date_due__lte=hours_ahead(HOURS)) 
    if requests: 
     one(requests) 
     two(requests) 
+3

请提供SSCCE([Short,Self Contained,Correct,Example](http://www.sscce.org/))代码。 – martineau

回答

1

我不能真正运行这个,但我认为这会对你说想要的东西,它创建了一个wrapper()函数调用原来(现在只返回一个对象列表),然后后处理它(但本身没有返回任何内容):

from functools import wraps 

def raw_turn_over_mailer(function): 
    @wraps(function) 
    def wrapper(requests): 
     object_list = function(requests) # call original 
     if object_list: 
      #.... 
    return wrapper 

@raw_turn_over_mailer 
def one(requests): 
    return [x for x in requests if x.account_type.name == 'AccountType1'] 

@raw_turn_over_mailer 
def two(requests): 
    return [x for x in requests if x.account_type.name == 'AccountType2'] 

这看起来像是一种复杂的方式来处理调用函数的结果。您可以调用后处理函数并将函数传递给对象列表。