简体   繁体   中英

python decorator, decorate a recursive function to run it many times

I have a recursive function (f calls itself):

def f(x) : 
    ....

I want to run this function multiple times. I use the following decorator:

def iter_f(func) : 
    def newf(x):
        for i in range(10):  
            func(x)
    return newf
@iter_f
def f(x): a RECURSIVE function.

When i call f(x), I am calling a function that iterate itself infinite times.I am curious what is the solution still using decorator, without wrap f inside a new function g, and decorate g.

Thanks.


Thanks for point out that the problem was due to f is recursive.


Decorating recursive functions in python this post has a similar problem, maybe this is not a good place to use decorator?

This should work

def iter_f(func):
    def newf(*args, **kwargs):
        for i in range(10):
            func(*args, **kwargs)
    return newf

@iter_f
def f(x):

Try this:

def iter_f(func) : 
    def newf(x):
        for i in range(10):  
            func(x)
    newf._original = func
    return newf


@iter_f
def f(x):
    ...
    call f._original(y)
    ...

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