i working through tutorial beginner's level python, , found can same result 1 less line of code, , don't know why instructor (he professional 15+ years) chose additional line/variable. assumption either has low-level use of urllib
library, and/or may programming best-practices, i'm hoping might able tell me why.
the function in question is:
from urllib.request import urlopen def load_page(url: str): response = urlopen(url) html = response.read().decode('utf') return html
as i've learned, returns actual html of request. while debugging , inspecting each piece of function does/returns, found can same result (the html of request) removing "response" variable completely:
def load_page(url: str): html = urlopen(url).read().decode('utf') return html
is there reason want first assign urlopen(url)
response
, instead of running read()
, decode()
directly on urlopen(url)
?
like functions should "do 1 thing" same said each line of code. there has been similar question (about broader concept of reducing line count on software engineering: "is fewer lines of code better?")
it's 1 operation make request, 1 operation contents of request.
from urllib.request import urlopen def load_page(url: str): response = urlopen(url) # make request html = response.read().decode('utf') # contents return html
this has number of advantages:
- debugging: if fails know fails (in terms of line number). did fail when doing
urlopen
or whendecode
? - extending code: want inspect
status
of response orheader
? easy, accessresponse.status
orresponse.headers
. - readability: more operations/calls there in 1 line harder understand line doing.
however in case "acceptable" read().decode(...)
in return line:
from urllib.request import urlopen def load_page(url: str): response = urlopen(url) # make request return response.read().decode('utf') # contents , return
Comments
Post a Comment