我的班级装饰器是否不够Pythonic或PyCharm在棉绒警告中不够聪明? [英] Is my in-class decorator not Pythonic enough or PyCharm not smart enough in lint warning?

查看:106
本文介绍了我的班级装饰器是否不够Pythonic或PyCharm在棉绒警告中不够聪明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个类中定义一个装饰器.我不想将其定义为单独的独立函数,因为此装饰器专门用于此类,所以我想将相关方法保持在一起.

I want to define a decorator within a class. I don't want to define it as a separated, independent function, for this decorator is specifically for this class and I want to keep the correlated methods together.

此装饰器的目的是检查某些先决条件,尤其是由成员变量保存的数据库连接,SSH连接等仍然可用.如果没有,则装饰函数将不会被调用,并且将完成一些错误报告和清理工作.

The purpose of this decorator is to check some prerequisites, especially the database connection, SSH connection, etc., which are held by member variables, are still available. If not, the decorated function won't be called and some error reporting and clean-up works will be done.

我制作了以下测试类来测试它是否有效,并且代码运行良好.但是我发现PyCharm对这段代码显示警告.所以我想知道这是否意味着我的代码不是Python语言,或者PyCharm不够聪明,并错误地发出了此警告?

I made the following testing class to test if it works, and the code did work well. But I found that PyCharm shows warnings to this piece of code. So I wonder, if it means that my code is not Pythonic, or PyCharm is not smart enough and gave this warning by mistake?

如果我的代码不是Pythonic,如何更改? 如果是PyCharm的错误,我和我的团队应如何配置PyCharm以使其在保留其他大多数皮棉检查的同时专门忽略这种警告?

If my code is is not Pythonic, how to change? If it is PyCharm's mistake, how shall I and my team configure PyCharm to let it specifically ignore this kind of warning while keep most other lint check?

class TestClass:
    def __init__(self):
        self.flag = True

    def dec(func):
        def wrapper(self, *args, **kwargs):
            if not self.flag:
                print("Won't run!")
                return empty_fun(self, *args, **kwargs)
            return func(self, *args, **kwargs)

        def empty_fun(*args, **kwargs):
            return None

        return wrapper

    @dec
    def foo(self):
        print("foo")

    @dec
    def bar(self, msg, more, *args, **kwargs):
        print("message: %s" % msg)
        print("more %s:" % more)
        for item in args:
            print("other item: %s" % item)
        name = kwargs.get('name')
        age = kwargs.get('age')
        print('name: %s' % name)
        print('age: %s' % age)


def main():
    t = TestClass()
    t.foo()
    print('-'*10)
    t.bar("abc", 'def', 'hij', 'klm', name='Tom', age=20)


if __name__ == '__main__':
    main()

这是PyCharm报告的皮棉警告:

Here is the lint warning reported by PyCharm:

推荐答案

您的代码在技术上是正确的(因为它可以按预期工作),但请注意,dec将成为TestClass的方法,并且会破坏如果这样调用.为避免这种情况,您至少应将其设为staticmethod.

Your code is technically correct (in that it will work as expected), with the caveat that dec will become a method of TestClass and will break if invoked as such. You should at least make it a staticmethod to avoid this.

wrt/pythonicity,在不需要此装饰器时,将其作为类的一部分确实是不Python的.它仅适用于此类的事实并不是使其成为该类成员的原因,更不用说使其成为公共API的一部分了.

wrt/ pythonicity, it IS indeed unpythonic to make this decorator part of the class when it's not needed. The fact it only applies to this class is not a reason to make it a member of the class, and even less to make it part of the public API.

您可能可以在注释中添加linter提示以使其静音,但是我个人只是从类中提取此装饰器,将其设置为私有,并记录它仅应与该类一起使用.

You can probably add linter hints in comments to silence it, but I'd personnally just extract this decorator from the class, make it private, and document that it's only supposed to be used with this class.

作为旁注:我假设您的empty_func是错误报告和清理工作"的占位符-否则,它只是无用的-但是确实需要在装饰器中对其进行定义吗?

As as side note: I assume your empty_func is a placeholder for the "error reporting and clean-up work" - else it's just plain useless -, but does it really need to be defined in the decorator?

这篇关于我的班级装饰器是否不够Pythonic或PyCharm在棉绒警告中不够聪明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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