Python 的通用编码风格?

发布于 2024-09-01 00:43:39 字数 631 浏览 4 评论 0原文

我对 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.- 我可以使用“importwhatever.functionasblah”吗?
我看到一些文件忽略了这样做。

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

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

你有什么可以推荐的吗?

I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now.

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

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-

<code here>

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

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.

Anything you would recommend?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

时光倒影 2024-09-08 00:43:39

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

Google 的 Python 样式指南 有一些部分经过深思熟虑,但是其他的则是特殊的(两空格缩进而不是流行的四空格缩进,以及函数和方法的 CamelCase 风格而不是 Camel_case 风格,都是相当主要的特质)。

关于您的具体问题:

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

80 列最受欢迎

2.- 使用什么引号? (我已经看到了一切,PEP 8 没有提到
任何清楚的事情)我正在使用单一
除文档字符串之外的所有内容的引号,
它使用三个双引号。

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

3.- 我把导入的东西放在哪里?我将它们放在文件头中
订单。

导入sys导入-python的其余部分
所需模块-

导入任何导入-其余部分
应用模块-

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

4.- 我可以使用“importwhatever.functionasblah”吗?我看到了一些
忽略这样做的文档。

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

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

最受欢迎。

6.- 变量命名风格?除了类之外,我对所有内容都使用小写,
我把它放在驼峰式命名法中。

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

PEP 8 is pretty much "the root" of all common style guides.

Google's Python style guide has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, are pretty major idiosyncrasies).

On to your specific questions:

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 columns is most popular

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.

I prefer the style you're using, but even Google was not able to reach a consensus about this:-(

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-

Yes, excellent choice, and popular too.

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

I strongly recommend you always import modules -- not specific names from inside a module. This is not just style -- there are strong advantages e.g. in testability in doing that. The as clause is fine, to shorten a module's name or avoid clashes.

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

Overwhelmingly most popular.

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

Almost everybody names classes with uppercase initial and constants with all-uppercase.

薄荷梦 2024-09-08 00:43:39

1.- 现在大多数人都有 16:9 或 16:10 显示器。即使它们没有宽屏,它们也有很多像素,80 列并不是一个很大的实际问题,就像每个人都在 4:3 显示器上的远程终端窗口中使用命令行一样。 320 X 240。我通常会在行太长时结束行,这是主观的。我在 23" 显示器 X 2.2 上的分辨率为 2048 X 1152。-

默认情况下使用单引号,因此您不必转义双引号,需要嵌入单引号时使用双引号,对于嵌入换行符的字符串使用三引号3.-

将它们放在文件的顶部,有时如果模块全局不需要它们,则将它们放在 ma​​in 函数中。

4.- 重命名某些内容是常见的习惯用法。下面是一个很好的例子,

try:
    # for Python 2.6.x
    import json
except ImportError:
    # for previous Pythons
    try:
        import simplejson as json
    except ImportError:
        sys.exit('easy_install simplejson')

但导入类或函数的首选方法是 from module import xxx ,如果需要,可以使用可选的 as yyy

5.- 始终只要没有 TABS,就使用空格!

6.- 类应为 UpperCaseCamelStyle,变量为小写,有时为 lowerCamelCase,有时为 all_lowecase_separated_by_underscores,“常量”应为 ALL_UPPER_CASE_SEPARATED_BY_UNDERSCORES

如有疑问,请参阅 PEP 8,Python 源代码,代码库中的现有约定。但最重要的是尽可能内部一致所有 Python 代码都应该尽可能看起来像是由同一个人编写的。

1.- Most everyone has a 16:9 or 16:10 monitor now days. Even if they don't have a wide-screen they have lots of pixels, 80 cols isn't a big practical deal breaker like it was when everyone was hacking at the command line in a remote terminal window on a 4:3 monitor at 320 X 240. I usually end the line when it gets too long, which is subjective. I am at 2048 X 1152 on a 23" Monitor X 2.

2.- Single quotes by default so you don't have to escape Double quotes, Double quotes when you need to embed single quotes, and Triple quotes for strings with embedded newlines.

3.- Put them at the top of the file, sometimes you put them in the main function if they aren't needed globally to the module.

4.- It is a common idiom to rename some modules. A good example is the following.

try:
    # for Python 2.6.x
    import json
except ImportError:
    # for previous Pythons
    try:
        import simplejson as json
    except ImportError:
        sys.exit('easy_install simplejson')

but the preferred way to import just a class or function is from module import xxx with the optional as yyy if needed

5.- Always use SPACES! 2 or 4 as long as no TABS

6.- Classes should up UpperCaseCamelStyle, variables are lowercase sometimes lowerCamelCase or sometimes all_lowecase_separated_by_underscores, as are function names. "Constants" should be ALL_UPPER_CASE_SEPARATED_BY_UNDERSCORES

When in doubt refer to the PEP 8, the Python source, existing conventions in a code base. But the most import thing is to be internally consistent as possible. All Python code should look like it was written by the same person when ever possible.

由于我对“样式”非常着迷,所以我将写下我目前在一个近 8k SLOC 项目中使用的指南,该项目包含大约 35 个文件,其中大部分与 PEP8 匹配。

  1. PEP8 说 79(WTF?),我选择 80,现在已经习惯了。毕竟眼球运动较少!

  2. 文档字符串和在 ''' 中跨越多行的内容。 '' 中的其他内容。另外,我不喜欢双引号,我一直只使用单引号...猜那是因为我来自 JavaScript 角落,在那里使用 '' 更容易,因为这样你就不必逃避所有HTML 内容 :O

  3. 位于头部,内置于自定义应用程序代码之前。但我也采用“早期失败”方法,因此,如果有某些依赖于版本的内容(例如 GTK),我会首先导入它。

  4. 取决于,大多数时候我都会使用 import foo 和 from foo import ,但在某些情况下(例如名称已经由另一个导入定义)我也使用 from foo import bar as bla 。

  5. 4 个空格。时期。如果您确实想使用制表符,请确保在使用 SCM 时将其转换为空格,然后再提交。但切勿(!)混合使用制表符和空格!它可能并且将会引入可怕的错误。

  6. some_method 或 foo_function,一个常量,MyClass。

此外,在方法调用或某些内容跨越多行的情况下,您还可以争论缩进,并且可以争论将使用哪种行延续样式。要么用 () 包围所有内容,要么在行尾添加 \ 。我选择后者,并且还将运算符和其他内容放置在下一行的开头。

# always insert a newline after a wrapped one
from bla import foo, test, goo, \
                another_thing

def some_method_thats_too_long_for_80_columns(foo_argument, bar_argument, bla_argument,
                                              baz_argument):

    do_something(test, bla, baz)

    value = 123 * foo + ten \
            - bla

    if test > 20 \
       and x < 4:

        test_something()

    elif foo > 7 \
         and bla == 2 \
         or me == blaaaaaa:

        test_the_megamoth()

另外,我还有一些比较操作的指南,我总是使用 is(not) 来检查 None True False 并且我从不进行像 if foo 这样的隐式布尔比较:,我总是这样做if foo is True:,动态类型很好,但在某些情况下我只是想确保它做正确的事情!

我做的另一件事是永远不要使用空字符串!它们位于常量文件中,在代码的其余部分中,我有诸如 username == UNSET_USERNAMElabel = UNSET_LABEL 这样的内容,这样更具描述性!

我也有一些严格的空白准则和其他疯狂的东西,但我喜欢它(因为我对它很疯狂),我什至编写了一个检查我的代码的脚本:
http://github.com/BonsaiDen/Atarashii/blob/master/checkstyle

警告(!):这会伤害你的感情!甚至比 JSLint 还要多......

但这只是我的 2 美分。

Since I'm really crazy about "styling" I'll write down the guidelines that I currently use in a near 8k SLOC project with about 35 files, most of it matches PEP8.

  1. PEP8 says 79(WTF?), I go with 80 and I'm used to it now. Less eye movement after all!

  2. Docstrings and stuff that spans multiple lines in '''. Everything else in ''. Also I don't like double quotes, I only use single quotes all the time... guess that's because I came form the JavaScript corner, where it's just easier too use '', because that way you don't have to escape all the HTML stuff :O

  3. At the head, built-in before custom application code. But I also go with a "fail early" approach, so if there's something that's version depended(GTK for example) I'd import that first.

  4. Depends, most of the times I go with import foo and from foo import, but there a certain cases(e.G. the name is already defined by another import) were I use from foo import bar as bla too.

  5. 4 Spaces. Period. If you really want to use tabs, make sure to convert them to spaces before committing when working with SCM. BUT NEVER(!) MIX TABS AND SPACES!!! It can AND WILL introduce horrible bugs.

  6. some_method or foo_function, a CONSTANT, MyClass.

Also you can argue about indentation in cases where a method call or something spans multiple lines, and you can argue about which line continuation style you will use. Either surround everything with () or do the \ at the end of the line thingy. I do the latter, and I also place operators and other stuff at the start of the next line.

# always insert a newline after a wrapped one
from bla import foo, test, goo, \
                another_thing

def some_method_thats_too_long_for_80_columns(foo_argument, bar_argument, bla_argument,
                                              baz_argument):

    do_something(test, bla, baz)

    value = 123 * foo + ten \
            - bla

    if test > 20 \
       and x < 4:

        test_something()

    elif foo > 7 \
         and bla == 2 \
         or me == blaaaaaa:

        test_the_megamoth()

Also I have some guidelines for comparison operations, I always use is(not) to check against None True False and I never do an implicit boolean comparison like if foo:, I always do if foo is True:, dynamic typing is nice but in some cases I just want to be sure that the thing does the right thing!

Another thing that I do is to never use empty strings! They are in a constants file, in the rest of the code I have stuff like username == UNSET_USERNAME or label = UNSET_LABEL it's just more descriptive that way!

I also have some strict whitespace guidelines and other crazy stuff, but I like it(because I'm crazy about it), I even wrote a script which checks my code:
http://github.com/BonsaiDen/Atarashii/blob/master/checkstyle

WARNING(!): It will hurt your feelings! Even more than JSLint does...

But that's just my 2 cents.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文