简体   繁体   中英

Decorator function to wrap a function?

I have to write a dummy function to get my code running on different systems, from which some don't have the needed packages. The function is wrapped and then called like a class -function. I am struggling with this problem, any ideas how to do that?

Here I got a short snippet, I import a python script ray.py which should contain this remote() function. The remote function has to take two arguments, without any usage.

Edit: The @ray.remote() wraps the run() function to be parallel executable. It doesn't change the return of run() . On some systems ray is not supported and I want the same script to execute sequentially without changing anything. Therefore I import a ray -dummy instead of the real one. Now I want to write the ray.remote() to wrap the run() function in a way so that it's callable with run.remote() .

That may be a very inconvenient method to just sequentially execute a function, but necessary to achieve an easy integration for different systems.

# here the wrapped function
@ray.remote(arg1, arg2)
def run(x):
    return x**2

# call it
squared = run.remote(2)

I got a working script, located in the ray.py file:

def remote(*args, **kwargs):
    def new_func(func):
        class Wrapper:
            def __init__(self, f):
                self.func = f

            def remote(self, *arg):
                out = self.func(*arg)
                return out
        ret = Wrapper(func)
        return ret

    return new_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