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?
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With