Tech Deviant Navigating the 21st century - Tech, Culture and more

Line joining and pep8 guidelines for maximum line length

The motivation behind writing this article came from a piece of code that I was working on earlier this week. It was a scrapper which uses a headless browser called, “PhantomJs”. I had to change the user agent in my HTTP requests and I found out an example to do just that. This is the example:

dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
    "(KHTML, like Gecko) Chrome/15.0.87"
)

When i first saw the above example, I thought it was a tuple being assigned to dcap. But when I took a closer look at it, I realized it was not the case. This is what I discovered:

Explicit vs Implicit line joining

In python, you can join two lines by ending that line with a, \. This is the explicit way of doing it.

dcap["phantomjs.page.settings.userAgent"] ="Mozilla/5.0 "\
    "(X11; Linux x86_64) "\
    "AppleWebKit/53 (KHTML, like Gecko) Chrome/15.0.87"

Now, if you want to do it implicitly, you’ll have to enclose the above string in parentheses, square brackets or curly braces:

dcap["phantomjs.page.settings.userAgent"] = (
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
    "(KHTML, like Gecko) Chrome/15.0.87"
)

Readability

If you look at the implicit way of writing statements then it is far more readable and less clutered. Though it might confuse the reader at first glance but in my opinion it looks cleaner.

PEP8

According to the PEP8 guidelines, the preferred way of wrapping long lines is through the implicit line joining using parentheses, square brackets or curly braces. So, here Implicit is better than Explicit but not in all the cases.


Comments !