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.
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.
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?
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()
Here is the lint warning reported by PyCharm: