【问题标题】:pylint: getting it to understand decoratorspylint:让它理解装饰器
【发布时间】:2017-03-01 07:32:46
【问题描述】:

pylint 似乎没有考虑装饰器。

我有一个这样的装饰器

@decorator
def foo(arg1, arg2):
    pass

变成

def foo(arg2):
    pass

但是 pylint 一直抱怨说,当我调用 foo 时,我错过了一个论点。我宁愿不禁用此警告,因为即使对于那些装饰功能也非常有用。有没有办法让它明白,伙计

【问题讨论】:

  • 但是警告不会消失吗?如果它理解我的意思。假设不是这样。
  • 你的意思是使用foo('one argument')的代码被标记为无效,因为装饰器传入了额外的参数?
  • 如果我写 foo('bar') 它会将 'bar' 解释为 arg1 并抱怨 missing argument arg2

标签: python python-decorators pylint


【解决方案1】:

如果你有类似的东西

def decorator(f):
    def wrapper(*args, **kwargs):
        return f(1, *args, **kwargs)
    return wrapper

@decorator
def z(a, b):
    return a + b

print( z(5) )

不要求对代码进行太多更改的简单解决方案是忘记@,这只是语法糖。它对我有用。

def z(a, b):
    return a + b
z = decorator(z)

print( z(5) )

【讨论】:

  • 这很好,也解决了 autospec 的模拟问题。对丑陋的语法感到羞耻。
【解决方案2】:

这是一个已知问题:https://github.com/PyCQA/pylint/issues/259

虽然它仍未修复,但除了使用 # pylint: disable=missing-kwoa 禁用检查之外,您唯一的选择是通过以下方式解决:

  1. 不使用 @decorator 语法,正如 polku 建议的那样;或
  2. 没有装饰器更改函数签名;或
  3. 提供默认值,即使它从未使用过或引发异常。

或者,4. 为 pylint 项目提供修复!

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2017-05-04
    • 2017-01-04
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多