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?
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:
(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 1Naturally, this is down to the purpose and audience of the code.