装饰器函数来包装一个函数? [英] Decorator function to wrap a function?

查看:46
本文介绍了装饰器函数来包装一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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.

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

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)

推荐答案

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

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

这篇关于装饰器函数来包装一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆