装饰器函数来包装一个函数?

时间:2020-12-29 14:25:01

标签: python decorator wrapper ray

我必须编写一个虚拟函数来让我的代码在不同的系统上运行,其中一些没有所需的包。该函数被包装,然后像 class 函数一样被调用。我正在努力解决这个问题,有什么想法可以做到吗?

这里有一个简短的片段,我导入了一个 python 脚本 ray.py,它应该包含这个 remote() 函数。 remote 函数必须接受两个参数,没有任何用法。

编辑:@ray.remote()run() 函数包装为并行可执行文件。它不会改变 run() 的返回值。在某些系统上不支持 ray,我希望相同的脚本按顺序执行而不更改任何内容。因此,我 import 是一个 ray-dummy 而不是真实的。现在我想编写 ray.remote() 以某种方式包装 run() 函数,以便它可以用 run.remote() 调用。

这可能是一种非常不方便的方法,只是顺序执行一个函数,但对于实现不同系统的轻松集成是必要的。

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

# call it
squared = run.remote(2)

1 个答案:

答案 0 :(得分:0)

我有一个工作脚本,位于 ray.py 文件中:

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
相关问题