函数调用的PEP8

2024-06-17 10:20:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始使用Python/Django,并且听说了pep8约定。在阅读了PEP8之后,我对如何“设计”我的代码有了更好的理解,但我学会了用Java编程,而且我以前只做我喜欢的任何事情。你能建议一下如何把我的例子放到PEP-8中吗?非常感谢。在

result = urllib.urlretrieve(
                            "https://secure.gravatar.com/avatar.php?"+
                            urllib.urlencode({
                                            'gravatar_id': hashlib.md5(email).hexdigest(),
                                            'size': srt(size)
                                            })
                            )

Tags: django代码size编程javaresulturllib事情
3条回答

这可能不是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的实用程序。在本例中,它将原始代码转换为

^{pr2}$

使用更多变量。不仅行更容易阅读,完整的代码也更容易理解:

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)

尝试下载代码风格的linter,比如pep8(一个检查代码是否符合pep8要求的程序)或pylint。您可以在这里找到更全面的Python样式检查程序列表和比较:What are the comprehensive lint checkers for 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 

代码的固定版本看起来更像这样:

^{pr2}$

从本质上讲,你违反政治公众人物8的主要原因是你缩进太多了。一次缩进是很好的,你不需要对齐函数调用的开始部分。Python还坚持行不能超过80个字符,但是修复过度缩进也解决了这个问题。在

相关问题 更多 >