Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Decorator function to wrap a function in Python

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, that it’s callable with run.remote(). That’s maybe 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 am thankful for any input!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...