【问题标题】:Python naming conventions in decorators装饰器中的 Python 命名约定
【发布时间】:2012-06-09 00:19:37
【问题描述】:

Python 装饰器的内部是否有任何“公认的”命名约定?

style guide 没有提及它,this awesome entry about decorators 在为返回的最终函数使用“包装”的变体方面非常一致,但是在创建带参数的装饰器时使用的名称呢?

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

具体来说,上例中innerfunctionwrapped的约定是什么?

【问题讨论】:

    标签: coding-style python


    【解决方案1】:

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

    但是,decorator 是装饰器函数 inner 的一个相当常见的名称。
    调用wrapped 函数wrapper 并用functools.wraps(f) 装饰它也很常见,f 是包装函数(func 也是它的常用名称)。

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

    【讨论】:

    • 呃,如果你有一个名为 decorator 的单参数函数,那么无论它叫什么,它的参数是什么都很清楚。
    • 调用内部函数decorator 可能是一个非常好的主意,因为decorator_name 并不是真正的装饰器,而是一个装饰器工厂,而且多层嵌套的函数定义可能有点混乱。
    • 为什么缩写function?我也问过这个here
    • @MikeStringer 我发现自己使用 f 或 _f 或 g 因为它符合数学符号(例如 f(x))并强调传递的函数本身不需要受到限制。 (相对于键函数或比较函数,或只接受一个参数的函数等)。
    【解决方案2】:

    根据定义,Python 中的装饰器可以是函数或类,因此实现的类型(类或函数)是决定使用哪种命名约定的因素。 一个常见的错误是在函数名称前加上关键字装饰器。 有关装饰器的更多信息,请参阅link

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 2011-03-03
      • 2013-10-16
      • 2010-09-15
      • 1970-01-01
      • 2014-12-13
      • 2020-11-09
      • 1970-01-01
      • 2012-03-17
      相关资源
      最近更新 更多