【问题标题】:Python- Share Variable Between Function and It's DecoratorPython-在函数和它的装饰器之间共享变量
【发布时间】:2014-03-03 01:54:13
【问题描述】:

(Python 2.7)由于装饰器不能与它们正在装饰的函数共享变量,我怎样才能将object_list 传递给装饰函数?我有一些函数将使用raw_turn_over_mailer() 装饰器,如果可能的话,我想将object_list 保留为本地装饰函数。

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)

【问题讨论】:

标签: python python-2.7 decorator python-decorators


【解决方案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']

这似乎是一种处理函数调用结果的复杂方式。您可以只调用后处理函数并将其传递给要调用的函数以获取对象列表。

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多