Search code examples
pythonpep8

PEP8 and long method names from imported modules


I can't seem to find a question on this, but I'm having issues maintaining PEP8 because of a module I've imported.

I'm using the TextGridTools (tgt) module to parse TextGrid files, format for annotating spoken audio files. The problem is it has functions with ghastly long names such as get_annotations_between_timepoints.

Because I'm using it inside a class method with loops, conditionals, and a list comprehension, it's already significantly indented:

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

Any suggestions?


Solution

  • You can break the line between parentheses with no ill effects. In fact, the official PEP-8 docs say as much:

    The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

    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
    

    An alternative would be to alias the long functions with a shorter local variable:

    get_tpts = att.get_annotations_between_timepoints
    

    Then use that alias where needed.