python - Python 的通用编码风格?

标签 python coding-style naming-conventions indentation column-width

我是 Python 的新手,我想开发我的第一个正式的开源项目。我想问一下python项目的通用编码风格是什么。我也会介绍我现在正在做的事情。

1.- 使用最广泛的列宽是多少? (永恒的问题)
我目前坚持使用 80 列(这很痛苦!)

2.- 使用什么引号? (我已经看到了所有内容,PEP 8 没有提到任何明确的内容)
除了文档字符串,我对所有内容都使用单引号,文档字符串使用三重双引号。

3.- 我应该把进口商品放在哪里?
我按此顺序将它们放在文件头。

import sys
import -rest of python modules needed-

import whatever
import -rest of application modules-

<code here>

4.- 我可以使用“import whatever.function as blah”吗?
我看到一些文件无视这样做。

5.- 用于缩进的制表符或空格?
当前使用 4 个空格选项卡。

6.- 变量命名风格? 我对除类以外的所有内容都使用小写字母,我将其放入驼峰式。

有什么推荐的吗?

最佳答案

PEP 8几乎是所有通用风格指南的“根源”。

谷歌的 Python style guide有一些部分是经过深思熟虑的,但其他部分是特殊的(两个空格的缩进而不是流行的四个空格的缩进,以及函数和方法的 CamelCase 样式而不是 camel_case 样式,是非常主要的特性)。

关于您的具体问题:

1.- What is the most widely used column width? (the eternal question) I'm currently sticking to 80 columns (and it's a pain!)

80列最受欢迎

2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear) I'm using single quotes for everything but docstrings, which use triple double quotes.

我更喜欢你使用的风格,但即使谷歌也无法就此达成共识:-(

3.- Where do I put my imports? I'm putting them at file header in this order.

import sys import -rest of python modules needed-

import whatever import -rest of application modules-

是的,很好的选择,也很受欢迎。

4.- Can I use "import whatever.function as blah"? I saw some documents that disregard doing this.

我强烈建议您始终导入模块——而不是模块内部的特定名称。这不仅仅是风格——还有强大的优势,例如这样做的可测试性。 as 子句可以缩短模块名称或避免冲突。

5.- Tabs or spaces for indenting? Currently using 4 spaces tabs.

绝对最受欢迎。

6.- Variable naming style? I'm using lowercase for everything but classes, which I put in camelCase.

几乎每个人都用大写首字母命名类,用全大写命名常量。

关于python - Python 的通用编码风格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2815272/

相关文章:

python - 比较矩阵中相邻单元格的更好方法

python - 属性错误: module 'pandas.io.sql' has no attribute 'frame_query'

库之间的 C 字符串转换

c# - 用于命名旨在替换现有 API 的 C# 类/方法的建议

sql - 如何正确命名记录创建(插入)日期时间字段?

python - 正则表达式与 Python re 从行尾开始匹配

python - 如何捕获 botocore 的 NoSuchKey 异常?

c - 在 C 语言中,为什么更多的函数比更复杂的函数更可取?

java - 更新方法中列表的参数 : return list or not

java - 扩展类时应该保留包名吗?