如何格式化符合PEP8的长断言语句?请忽略我的例子中人为的本性。
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), 'some_param_name must be an instance of SomeClassName, silly goose!'
不能将它包装在括号中,因为这会改变assert语句的行为,因为它是关键字,而不是内置函数。
答案 0 :(得分:51)
重要的是要记住,PEP8只是一个指导原则even states that there are times when the rules should be broken。
但最重要的是:知道何时不一致 - 有时风格指南并不适用。
考虑到这一点,我可能会用旧式续行来写这个:
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), \
'some_param_name must be an instance of SomeClassName, silly goose!'
如果这与你(或你的短信)并不合适,你可以随时做到:
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), (
'some_param_name must be an instance of SomeClassName, silly goose!')
甚至:
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), (
'some_param_name must be an instance of SomeClassName, '
'silly goose!')
答案 1 :(得分:5)
ERR_MESSAGE_01 = '''
Some really long error message
'''
assert condition(a,b), ERR_MESSAGE_01
我是怎么做的......而且我觉得这很合适......
答案 2 :(得分:3)
值得注意的是,可以用括号括起来,而不是用你想的方式。
assert isinstance(some_param_name,
SomeClassName), ('some_param_name must be an instance of '
'SomeClassName, silly goose!')
但是,我不认为它特别易读。在某些情况下,它可能是正确的选择。
答案 3 :(得分:1)
def afunc(some_param_name):
assert (isinstance(some_param_name, SomeClassName)
), 'some_param_name must be an instance of SomeClassName, silly goose!'
这样就可以在不破坏断言行为的情况下,从PEP 8推荐的括号中获得隐含的行继续。
可替换地:
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), (
'some_param_name must be an instance of SomeClassName, silly goose!')
答案 4 :(得分:0)
在Maximum Line Length部分结尾的pep8中对此进行了描述。
反斜杠有时仍然合适。例如,[...]另一种情况是使用assert语句。
因此,建议使用pep8作为第一个示例,例如:
def afunc(some_param_name):
assert isinstance(some_param_name, SomeClassName), \
'some_param_name must be an instance of SomeClassName, silly goose!'