简体   繁体   English

如何制作一个虚拟的无操作 @jit 装饰器?

[英]How do I make a dummy do-nothing @jit decorator?

I want numba to be an optional dependency, so that it's fast if installed or slow if not.我希望 numba 成为一个可选的依赖项,这样如果安装它就很快,如果没有安装它就很慢。 So when numba is not installed, I want @njit to be a dummy decorator that does nothing.因此,当未安装 numba 时,我希望@njit成为一个什么都不做的虚拟装饰器。

If I follow these directions and use:如果我遵循这些指示并使用:

def njit(func):
    return func

Then when the decorator is called like @njit(cache=True, nogil=True) I get errors about:然后,当像@njit(cache=True, nogil=True)这样调用装饰器时,我会收到以下错误:

TypeError: njit() got an unexpected keyword argument 'cache'

If I try to catch the args and ignore them using如果我尝试捕获 args 并使用忽略它们

    def njit(func, *args, **kwargs):
        return func

then I get:然后我得到:

missing 1 required positional argument: 'func'

How do I just make a dummy decorator that does nothing and ignores kwargs?我如何制作一个什么都不做并忽略 kwargs 的虚拟装饰器?

Think of decorators with arguments as decorator factory, they return a decorator.将带参数的装饰器视为装饰器工厂,它们返回一个装饰器。 This way这边走

def decorator(func):
    return func

The above is a decorator, now with arguments上面是一个装饰器,现在有参数

def decorator_factory(a,b,c):
    def decorator(func):
        return func
    return decorator

The inner decorator has access to the a,b,c arguments because is a closure.内部decorator可以访问a,b,c参数,因为它是一个闭包。 I hope that helps我希望有帮助


So it can be defined as:所以可以定义为:

def njit(cache, nogil):
    def decorator(func):
        return func 
    return decorator

If you want to save some time and be able to do the same with all numba decorators, try numbasub .如果您想节省一些时间并能够对所有 numba 装饰器执行相同操作,请尝试numbasub It provides exactly what you are asking for, and you can apply it to any project you want.它准确地提供了您所要求的内容,您可以将其应用到您想要的任何项目中。

Expanding on geckos' answer, we can adapt it to be compatible with @njit as well.扩展 geckos 的答案,我们也可以将其调整为与 @njit 兼容。

The code for jit can be found in https://github.com/numba/numba/blob/main/numba/core/decorators.py jit 的代码可以在https://github.com/numba/numba/blob/main/numba/core/decorators.py中找到

What we need to do is to make jit act as a factory decorator when used as @jit() and as a simple decorator when used as @jit.我们需要做的是让 jit 在用作 @jit() 时充当工厂装饰器,在用作 @jit 时充当简单装饰器。

def njit(f=None, *args, **kwargs):
    def decorator(func):
        return func 

    if callable(f):
        return f
    else:
        return decorator

This should work in both cases.这应该在这两种情况下都有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM