1

(Python 2.7)Since decorators can not share variables with the function they are decorating, how can I make/pass object_list to the decorating function? I have a few of functions that will be using raw_turn_over_mailer() decorator and I would like to keep object_list to the local decorated function if possible.

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)
1

1 Answer 1

1

I can't actually run this, but I think it would do what you say want, It creates awrapper()function that calls the original (which now just returns an object list) and then post-processes it (but returns nothing itself):

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']

This seems like a convoluted way to process the results of calling a function. You could just call the post-processing function and pass it the function to call to get the object list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.