我通常会为我的模块声明一个基本的异常,该异常不会执行任何操作,因为我会衍生出可能包含其他自定义数据的自定义错误:AFAIK,这是在Python中使用exeptions的Right Way™。
我还习惯于从该自定义信息中构建一条人类可读的消息并将其传递,因此我可以在错误处理程序中引用该消息。这是一个示例:
# this code is meant to be compatible with Python-2.7.x
class MycoolmoduleException(Exception):
'''base Mycoolmodule Exception'''
class TooManyFoo(MycoolmoduleException):
'''got too many Foo things'''
def __init__(self, foo_num):
self.foo_num = foo_num
msg = "someone passed me %d Foos" % foo_num
super(TooManyFoo, self).__init__(msg)
# .... somewhere else ....
try:
do_something()
except Exception as exc:
tell_user(exc.message)
# real world example using Click
@click.command()
@click.pass_context
def foo(ctx):
'''do something'''
try:
# ... try really hard to do something useful ...
except MycoolmoduleException as exc:
click.echo(exc.message, err=True)
ctx.exit(-1)
现在,当我通过pylint-2.3.1
运行该代码时,它抱怨我使用MycoolmoduleException.message
:
coolmodule.py:458:19: E1101: Instance of 'MycoolmoduleException' has no 'message' member (no-member)
这种代码始终对我有用(在Python2和Python3中都是这样),而在同一代码中的hasattr(exc, 'message')
返回True
,那么为什么pylint会抱怨呢?和/或:如何改进该代码?
(注意,如果我尝试捕获内置Exception
而不是我自己的MycoolmoduleException
,也会发生同样的情况)