大名鼎鼎的Requests库用了什么编码风格?

原文:https://www.kennethreitz.org/essays/kenneth-reitzs-code-stylepython

做者:Kenneth Reitzdom

原题:Kenneth Reitz’s Code Style™ide

 

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。千万别。请。code

文档字符串(docstrings)应遵循如下语法:对象

def the_earth_is_flat():
    """NASA divided up the seas into thirty-three degrees."""
    pass

def 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__),这些是此规则的例外。three

Thanks for helping to make the world a better place!ci

资料来源(译注:即 Requests 的开发者指南):http://t.cn/E5VgNJF

(译文完)

K 神的这篇文章很短,实际上,这只是摘自 Requests 的开发者指南的一小部分。

可是,关于灵活设定行长的部分,我举双手双脚赞同。若是你所在的公司有“清白盒”的优良传统(不只指Python),那你极有可能遇到被迫换行的麻烦,而实际上才仅仅刚刚超出了几个字符。那时候,你就会明白,这 3 条灵活规则的好处了。

另外,关于连续行的部分,PEP-8 相关内容在:http://t.cn/Rq4mxOo

PEP-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+本精选电子书。

相关文章
相关标签/搜索