我似乎找不到这个问题,但是由于导入的模块,我在维护PEP8时遇到问题。
我正在使用TextGridTools(tgt)模块来解析TextGrid文件,该格式用于注释语音文件。问题在于它具有可怕的长名称功能,例如get_annotations_between_timepoints
。
因为我在带有循环,条件和列表理解的类方法中使用它,所以它已经缩进了:
def align_intervals(self):
print('Aligning intervals...')
brk = self.brk_intervals
all_atts = self.all_attributes
word_list = []
for i in range(len(brk)):
if i == 0:
word_list.append([att.get_annotations_between_timepoints(0, brk[0].time) for att in all_atts])
else:
word_list.append([att.get_annotations_between_timepoints(brk[i-1].time, brk[i].time) for att in all_atts])
return word_list
有什么建议吗?
答案 0 :(得分:1)
您可以中断括号之间的界线,而不会产生不良影响。实际上,PEP-8官方文档这么说:
包裹长行的首选方法是在括号,方括号和花括号内使用Python的隐含行连续性。通过将表达式包装在括号中,可以将长行分成多行。应该优先使用这些字符,而不是使用反斜杠来继续行。
def align_intervals(self):
print('Aligning intervals...')
brk = self.brk_intervals
all_atts = self.all_attributes
word_list = []
for i in range(len(brk)):
if i == 0:
word_list.append([
att.get_annotations_between_timepoints(
0, brk[0].time
) for att in all_atts
])
else:
word_list.append([
att.get_annotations_between_timepoints(
brk[i - 1].time, brk[i].time
) for att in all_atts
])
return word_list
另一种选择是用较短的局部变量为长函数别名:
get_tpts = att.get_annotations_between_timepoints
然后在需要的地方使用该别名。
答案 1 :(得分:1)
您可以自己给长方法名起短名:
import package
short_method = package.ungodly_ridiculous_long_name_for_a_method
short_class = package.another_ungodly_unnecessarily_long_name_for_a_class
答案 2 :(得分:0)
是的,只需插入一些换行符即可:
def align_intervals(self):
print('Aligning intervals...')
brk = self.brk_intervals
all_atts = self.all_attributes
word_list = []
for i in range(len(brk)):
if i == 0:
word_list.append(
[
att.get_annotations_between_timepoints(0, brk[0].time)
for att in all_atts
]
)
else:
word_list.append(
[
att.get_annotations_between_timepoints(brk[i-1].time, brk[i].time)
for att in all_atts
]
)
return word_list
对于代码样式,没有明确的答案,因为毕竟这是主观的。 Black
最近推出了一个非常漂亮的IMO代码格式化程序。但最后,只要做您/您的团队最喜欢的事情即可。
答案 3 :(得分:0)
几个选项:
因此您可以替换
word_list = []
for i in range(len(brk)):
if i == 0:
word_list.append([
att.get_annotations_between_timepoints(
0, brk[0].time
) for att in all_atts
])
else:
word_list.append([
att.get_annotations_between_timepoints(
brk[i - 1].time, brk[i].time
) for att in all_atts
])
使用
def gabt(brk0, brk1, all_atts):
att_gabt = att.get_annotations_between_timepoints
return [att_gabt(brk0.time, brk1.time) for att in all_atts]
word_list = [gabt(0, brk[0].time, all_atts)]
for brk0, brk1 in zip(brk[:-1], brk[1:]):
word_list.append(gabt(brk0.time, brk1.time, all_atts))
因为它在一个类中,所以重构后的代码可能看起来像这样:
def _gabt(self, brk0, brk1):
att_gabt = att.get_annotations_between_timepoints
return [att_gabt(brk0.time, brk1.time) for att in self.all_attributes]
word_list = [self._gabt(0, brk[0].time)]
for brk0, brk1 in zip(brk[:-1], brk[1:]):
word_list.append(self._gabt(brk0.time, brk1.time))