我最近开始使用Python/Django,我听说了PEP 8的约定。在阅读了PEP8之后,我对如何‘风格’我的代码有了更好的理解,但是我学会了用Java编程,我过去只做我喜欢做的事情。你能建议怎样把我的例子写进PEP-8吗?非常感谢。
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?"+
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)发布于 2014-09-08 13:31:34
尝试下载代码样式指针,如pep8 (一个检查您的代码以查看它是否符合PEP 8要求的程序)或pylint。您可以在这里找到一个更全面的Python样式检查器列表和比较:Python的综合检查程序是什么?
事实上,网上有一个pep8检查程序:http://pep8online.com/
如果我们在其中运行您的代码,它会告诉您:
Code Line Column Text
E126 2 29 continuation line over-indented for hanging indent
E225 2 70 missing whitespace around operator
E126 4 45 continuation line over-indented for hanging indent
E501 4 80 line too long (90 > 79 characters)
W292 7 30 no newline at end of file 您的代码的固定版本看起来更像这样:
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?" +
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)本质上,主要的PEP 8违规行为是你缩得太多了。一个缩进就可以了--你不需要对齐函数调用的开头部分。Python还坚持您的行不超过80个字符,但是修复过度缩进也解决了这个问题。
发布于 2014-09-08 13:34:06
使用更多的变量。不仅行更容易阅读,完整的代码也更容易理解:
base = "https://secure.gravatar.com/avatar.php"
params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)})
url = "{}?{}".format(base, params)
result = urllib.urlretrieve(url)发布于 2014-09-08 13:30:15
这可能不是PEP8建议的,但是为了提高可读性,您可以如下所示:
base = "https://secure.gravatar.com/avatar.php?"
params = urllib.urlencode({'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)})
result = urllib.urlretrieve(base+params) 请注意,autopep8是一个用于格式化Python代码以符合PEP8的实用工具。在本例中,它将原始代码转换为
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?" +
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)https://stackoverflow.com/questions/25725336
复制相似问题