Search code examples
pythonline-breakspep8

How to deal with long lines of code and commands in Python


I've tried searching, but I couldn't find any situations similar to mine. I am writing a program and so far I've stuck to the no more than 79 characters in a line rule. However I'm not sure where to break lines in a few situations.

Here are the problem areas:

        self.proc.stdin.write('(SayText "%s")\n' % text.replace('\\', '\\\\').replace('"', '\\"'))

For this situation when I break first line after the '(SayText "%s")\n', the second line ends up being 80 characters long. Should I then break the second line somewhere in the brackets like this?

        self.proc.stdin.write('(SayText "%s")\n'
                              % text.replace('\\',
                                             '\\\\').replace('"', '\\"'))

Or would it be better to bring the entire third line to the beginning of the first brackets like this:

        self.proc.stdin.write('(SayText "%s")\n'
                              % text.replace('\\',
                              '\\\\').replace('"', '\\"'))

Another example of this is here:

        filename = tkFileDialog.askopenfilename(filetypes = (("Word list", "*.tldr"), ("All files", "*.*")))

Should I do this?

        filename = tkFileDialog.askopenfilename(filetypes = (("Word list",
                                                              "*.tldr"),
                                                             ("All files",
                                                              "*.*")))

Or this?

        filename = tkFileDialog.askopenfilename(filetypes = (("Word list",
                                                "*.tldr"),("All files", "*.*")))

What would be a good convention to follow?

Thanks.


Solution

  • In my opinion, one of the reasons to prefer shorter lines is that it makes the programmer more likely to break up code into individual shorter lines which are easier to understand and to spot errors or better ways to do things in.

    from __future__ import print_function    
    
    FMT_SAY_TEXT = '(SayText "%s")'
    

    text_escaped = text.replace('\\', r'\\')
    text_escaped = text_escaped.replace('"', r'\"')
    text_out = FMT_SAY_TEXT % text_escaped
    print(text_out, file=self.proc.stdin)
    

    For your second example:

    FILE_DIALOG_FILETYPES = (("Word list", "*.tldr"), ("All files", "*.*"))
    

    filename = tkFileDialog.askopenfilename(filetypes = FILE_DIALOG_FILETYPES)