Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best python style for complex one-liners

I recently wrote a rather ugly looking one-liner, and was wondering if it is better python style to break it up into multiple lines, or leave it as a commented one-liner. I looked in PEP 8, but it did not mention anything about this

This is the code I wrote:

def getlink(url):
    return(urllib.urlopen(url).readlines()[425].split('"')[7])
    # Fetch the page at "url", read the 426th line, split it along
    # quotes, and return the 8th quote delimited section

But would something like this be better style?:

 def getlink(url):
    url_file = urllib.urlopen(url)
    url_data = url_file.readlines()
    line = url_data[425]
    line = line.split('"')
    return line[7]

Or perhaps something in between?

like image 818
Strigoides Avatar asked Aug 23 '11 08:08

Strigoides


People also ask

Can Python code be written in one line?

Practical Data Science using PythonThese statements can very well be written in one line by putting semicolon in between. However, this practice is not allowed if there is a nested block of statements.

What is PEP 8 and why is it important?

PEP 8, sometimes spelled PEP8 or PEP-8, is a document that provides guidelines and best practices on how to write Python code. It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. The primary focus of PEP 8 is to improve the readability and consistency of Python code.


2 Answers

My vote would be based on readability. I find your one-liner quicker to digest than the multi-line example.

One-liners are great as long as it fits in one eye-ful, and collectively they perform one distinct task.

Personally, I would write that as:

def getlink(url):
    content = urllib.urlopen(url).readlines()  
    return content[425].split('"')[7]  

(Now, venturing into downvote realm...)

Your block of comments is great for someone unfamiliar with Python, but arguably, they reduce readability by increasing the information to digest. A pythonista reading the code would quickly understand your one-liner, and yet may then proceed to read the comments just in case there are caveats or edge cases to be warned of.

I'm not saying comments are evil, just that verbose comments can have a negative effect on readability. E.g. the classic : x+=1 # increment x by 1

Naturally, this is down to the purpose and audience of the code.

like image 140
Shawn Chin Avatar answered Oct 18 '22 13:10

Shawn Chin


I also find the expression urllib.urlopen(url).readlines()[425].split('"')[7] rather comprehensible.

However, I would prefer:

def getlink(url):
    line425 = urllib.urlopen(url).readlines()[425]
    return line425.split('"')[7]
like image 29
eyquem Avatar answered Oct 18 '22 13:10

eyquem