Python在装饰器中的命名约定 [英] Python naming conventions in decorators

查看:737
本文介绍了Python在装饰器中的命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python装饰器的内部是否有任何接受的命名约定?

Are there any "accepted" naming conventions for the innards of Python decorators?

样式指南没有提及,还有这个真棒条目装饰器在使用包装的变体作为返回的最终函数时非常一致,但是当创建接受参数的装饰器时使用的名称如何?

The style guide doesn't mention it, and this awesome entry about decorators is pretty consistent in using variants of "wrapped" for the ultimate function that is returned, but what about the names used when creating decorators that take arguments?

def decorator_name(whatevs):
    def inner(function):
        def wrapped(*args, **kwargs):
            # sweet decorator goodness
        return wrapped
    return inner

具体来说,<$ c在上面的例子中,$ c> inner , function wrapped >

Specifically, what are the conventions for inner, function, and wrapped in the above example?

推荐答案

这些名称没有标准化的约定(如PEP)。如果你检查python stdlib,你会发现这些函数有很多不同的名字。

There are no standardized conventions (such as PEPs) for those names. If you check the python stdlib you'll find lots of different names for those functions.

但是, decorator 一个很常见的名称为装饰器函数 inner

这也是常见的调用 wrapped 函数 wrapper ,并使用 functools.wraps(f) ,其中 f 是包装函数( func 也是一个常见的名称)。

However, decorator is a rather common name for the decorator function inner.
It is also common to call your wrapped function wrapper and decorate it with functools.wraps(f) with f being the wrapped function (func is also a common name for it).

def decorator_name(whatevs):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            pass # sweet decorator goodness
        return wrapper
    return decorator

这篇关于Python在装饰器中的命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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