原文:https://www.kennethreitz.org/…作者:Kenneth Reitz原题:Kenneth Reitz’s Code Style™Requests 的代码库使用 PEP-8 编码风格。除了 PEP-8 中列出的标准外,我们还有一些指导原则:如果方便的话,行长(Line-length)可超过 79 个字符,达到 100 个字符。如果换行会导致严重的不方便,则行长可以超过 100 个字符。除非在字符串中出现单引号,否则始终使用单引号字符串(例如,’#flatearth’)。此外,PEP-8 推荐的用于连续行的编码风格毫无一点品味,绝不允许在 Requests 代码库使用:# 与开局定界符对齐foo = long_function_name(var_one, var_two, var_three, var_four)No。千万别。请。文档字符串(docstrings)应遵循以下语法:def the_earth_is_flat(): “““NASA divided up the seas into thirty-three degrees.””” passdef fibonacci_spiral_tool(): “““With my feet upon the ground I lose myself / between the sounds and open wide to suck it in. / I feel it move across my skin. / I’m reaching up and reaching out. / I’m reaching for the random or whatever will bewilder me. / Whatever will bewilder me. / And following our will and wind we may just go where no one’s been. / We’ll ride the spiral to the end and may just go where no one’s been. Spiral out. Keep going… "”” pass所有函数、方法和类都要求包含 docstrings 。除了对象数据模型方法(例如,repr),这些是此规则的例外。Thanks for helping to make the world a better place!资料来源(译注:即 Requests 的开发者指南):http://t.cn/E5VgNJF(译文完)K 神的这篇文章很短,实际上,这只是摘自 Requests 的开发者指南的一小部分。但是,关于灵活设定行长的部分,我举双手双脚赞同。如果你所在的公司有“清白盒”的优良传统(不仅指Python),那你极有可能遇到被迫换行的麻烦,而实际上才仅仅刚刚超出了几个字符。那时候,你就会明白,这 3 条灵活规则的好处了。另外,关于连续行的部分,PEP-8 相关内容在:http://t.cn/Rq4mxOoPEP-8 反对的是如下写法:# Arguments on first line forbidden when not using vertical alignment.# 不使用垂直对齐的参数禁止在第一行上foo = long_function_name(var_one, var_two, var_three, var_four)PEP-8 推荐的写法是垂直地将换行的参数对齐起始的参数:# 与开局定界符对齐foo = long_function_name(var_one, var_two, var_three, var_four)K 神反对了 PEP-8 推荐的写法。在我看来,任何有品味的人,都会反对以上的两种写法。即使一个方法的参数超级多,超出了 100 个字符,我本人也是极不情愿换行的。所以,K 神的说法深得我心。关于代码风格,没有绝对完全一致的标准。本文也不想引起争论。不过,我认同 K 神设定的规则,因为一种与主流不同的审美倾向,值得发现它的同类。—————–本文原创并首发于微信公众号【Python猫】,后台回复“爱学习”,免费获得20+本精选电子书。