简体   繁体   中英

Recursive decorator reinitializing attributes

Suppose we have a decorator for recursive function:

def decorator(func):

    def wrapper(*args, **kwargs):
        ...
        res = func(*args, **kwargs)
        ...
        return res

    func.a = 0
    wrapper.a = 0
    return wrapper

I want to reinitialize .a attributes every time I call func on the first step of recursion (so when func calls itself, .a attributes are not being changed). Can I implement it somehow in decorator?

This is not possible with a decorator. They are designed to completely take over the implementation of func so that all calls go through the wrapper.

What you require is that just the first call reinitialises the .a attribute, which sounds like you want some sort of forwarding:

def fwd_func(*args, **kwargs):
    func.a = 0
    ...
    res = func(*args, **kwargs)
    ...
    return res

Now, just the top level callers should call fwd_func(...) instead of func(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM