`
tmj_159
  • 浏览: 705823 次
  • 性别: Icon_minigender_1
  • 来自: 永州
社区版块
存档分类
最新评论

Python Code Style

 
阅读更多

本文翻译自Google文档

http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Python_Style_Rules

 

说明

本文风格是Google内部的Python代码风格。

 

1. 分号

如果一句代码有多行,不要在每行后面使用分号 ,并且不要通过分号把多句代码放一行

 

2. 行长度

80

 

3.圆括号

节约使用(意思能不使用不使用,除非有特殊用途),举例

Yes: if foo:
         bar()
     while x:
         x = bar()
     if x and y:
         bar()
     if not x:
         bar()
     return foo
     for (x, y) in dict.items(): ...

No:  if (x):
         bar()
     if not(x):
         bar()
     return (foo)

 

4. 缩进

4个字符

 

5. 空白行

在两个最高成的定义之间使用两个空白行,在不同的方法之间使用一个空白行

 

6.空格

圆括号,方括号,花括号之间没有空格

Yes: spam(ham[1], {eggs: 2}, [])

No:  spam( ham[ 1 ], { eggs: 2 }, [ ] )

 逗号,分号,冒号之前没有空格,在之后加上一个空格,除非在行的末尾了

Yes: if x == 4:
         print x, y
     x, y = y, x

No:  if x == 4 :
         print x , y
     x , y = y , x

圆括号,方括号之前没有空格

 

Yes: spam(1)

No:  spam (1)

Yes: dict['key'] = list[index]

No:  dict ['key'] = list [index]

 不用在等号两边使用空格,当在区分参数和设置默认值的时候

Yes: def complex(real, imag=0.0): return magic(r=real, i=imag)

No:  def complex(real, imag = 0.0): return magic(r = real, i = imag)

 不要使用空格做额外的对齐操作

Yes:
  foo = 1000  # comment
  long_name = 2  # comment that should not be aligned

  dictionary = {
      'foo': 1,
      'long_name': 2,
  }

No:
  foo       = 1000  # comment
  long_name = 2     # comment that should not be aligned

  dictionary = {
      'foo'      : 1,
      'long_name': 2,
  }

 

7. Shebang Line (组织行 )

大部分.py文件不需要以#!开头,除了主文件(即入口文件)要以#!/usr/bin/python开头。

这个开头是用来给内核找python的解释器用的。

 

8. 注释,文档说明

Modules 应该加上license文件

Functions and methods 应该加上注释除非满足如下条件

1.外部不可见

2.非常短

3.很明显

如下,注释模板来自bigtable

def fetch_bigtable_rows(big_table, keys, other_silly_variable=None):
    """Fetches rows from a Bigtable.

    Retrieves rows pertaining to the given keys from the Table instance
    represented by big_table.  Silly things may happen if
    other_silly_variable is not None.

    Args:
        big_table: An open Bigtable Table instance.
        keys: A sequence of strings representing the key of each table row
            to fetch.
        other_silly_variable: Another optional variable, that has a much
            longer name than the other args, and which does nothing.

    Returns:
        A dict mapping keys to the corresponding table row data
        fetched. Each row is represented as a tuple of strings. For
        example:

        {'Serak': ('Rigel VII', 'Preparer'),
         'Zim': ('Irk', 'Invader'),
         'Lrrr': ('Omicron Persei 8', 'Emperor')}

        If a key from the keys argument is missing from the dictionary,
        then that row was not found in the table.

    Raises:
        IOError: An error occurred accessing the bigtable.Table object.
    """
    pass

 类的注释

class SampleClass(object):
    """Summary of class here.

    Longer class information....
    Longer class information....

    Attributes:
        likes_spam: A boolean indicating if we like SPAM or not.
        eggs: An integer count of the eggs we have laid.
    """

    def __init__(self, likes_spam=False):
        """Inits SampleClass with blah."""
        self.likes_spam = likes_spam
        self.eggs = 0

    def public_method(self):
        """Performs operation blah."""

 内部块注释

# We use a weighted dictionary search to find out where i is in
# the array.  We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.

if i & (i-1) == 0:        # true iff i is a power of 2

 

 9. 类

如果一个类不继承其它的类,应该明确的继承object,就算是内部类也应该这么做

Yes: class SampleClass(object):
         pass


     class OuterClass(object):

         class InnerClass(object):
             pass


     class ChildClass(ParentClass):
         """Explicitly inherits from another class already."""

No: class SampleClass:
        pass


    class OuterClass:

        class InnerClass:
            pass

 这样可以避免一些潜在错误。

 

10 字符串

使用格式化方法或者%操作符来格式化字符串,即便你知道所有的参数都是字符串,判断好什么时候该用+,什么时候用%.

Yes: x = a + b
     x = '%s, %s!' % (imperative, expletive)
     x = '{}, {}!'.format(imperative, expletive)
     x = 'name: %s; score: %d' % (name, n)
     x = 'name: {}; score: {}'.format(name, n)

No: x = '%s%s' % (a, b)  # use + in this case
    x = '{}{}'.format(a, b)  # use + in this case
    x = imperative + ', ' + expletive + '!'
    x = 'name: ' + name + '; score: ' + str(n)

 避免在循环中使用+,和+=,因为string 是不可以变的,这样会创建出很多不必要的临时对象。相反,在循环结束是用''.join 来将一个list变成string(或者将每个子字符串写进io.BytesIO 缓冲区)

Yes: items = ['<table>']
     for last_name, first_name in employee_list:
         items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
     items.append('</table>')
     employee_table = ''.join(items)

No: employee_table = '<table>'
    for last_name, first_name in employee_list:
        employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
    employee_table += '</table>'

 坚持使用一种风格的字符串符号

Yes:
  Python('Why are you hiding your eyes?')
  Gollum("I'm scared of lint errors.")
  Narrator('"Good!" thought a happy Python reviewer.')

No:
  Python("Why are you hiding your eyes?")
  Gollum('The lint. It burns. It burns us.')
  Gollum("Always the great lint. Watching. Watching.")

 

11. 文件和套接字

但处理完file 和socket 的时候一定记得关闭它们。

file, socket或者类文件的对象不必要的打开有下面这个缺点。

1. 消耗系统有限的资源,例如文件句柄。

2. 占用文件会阻止其它的的操作,例如移动和删除。

3. 他们在整个程序都是全局共享的,关闭会导致读和写出现异常。

虽然在对象离开生命周期的时候会自动销毁,但是不建议通过这种方式来处理。下面是原因

1. 首先这种方式没有保证,因为不同Python实现使用不同的内存管理技术,比如说延迟内存回收。

2. 没有预料到的应用会保持这些对象更加长的时间不被处理。

首选的方法管理文件是使用"with" 语句

with open("hello.txt") as hello_file:
    for line in hello_file:
        print line

 类文件的对象不支持"with"语句,使用contextlib.closing().

import contextlib

with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page:
    for line in front_page:
        print line

 Pythone 2.5 可以使用 "with" 语句

from __future__ import with_statement

 

12 TODO 注释的使用

为暂时的,短期的解决方案,不够完美的代码使用TODO来标识。

 

13 Import的格式

不同的import 应该在不同行

Yes: import os
     import sys

No:  import os, sys

 引入比较多的时候应该分组,分组规则如下

1. 标准库

2. 第三方库

3. 应用级别的库

 

14 属性访问控制

但一个属性访问比较复杂或者,应该使用方法调用类似get_foo(), 和set_foo()来代替的。

 

15 命名

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name. 

 Guido推荐的命名方式

Type Public Internal
Packages lower_with_under  
Modules lower_with_under _lower_with_under
Classes CapWords _CapWords
Exceptions CapWords  
Functions lower_with_under() _lower_with_under()
Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER
Global/Class Variables lower_with_under _lower_with_under
Instance Variables lower_with_under _lower_with_under (protected) or __lower_with_under (private)
Method Names lower_with_under() _lower_with_under() (protected) or __lower_with_under() (private)
Function/Method Parameters lower_with_under  
Local Variables lower_with_under  

 

16 Main

在Python, pydoc 和unit test 需要可被导入的modules,在执行你的程序之前,你的代码总应该做检查,这样可以避免你的module被引入的时候main 程序不被调用

 

def main():
      ...

if __name__ == '__main__':
    main()

 

17 最后的话

保持一致性。

如果你在编辑代码,花一点时间去其他代码看看它们的风格,和他们保持一致。

分享到:
评论

相关推荐

    python code style

    1. **PEP 8: Python Code Style Guide**:PEP 8 是Python官方推荐的代码风格指南,它提供了一系列关于如何编写清晰、一致的Python代码的指导原则。例如,使用空格来分隔操作符和括号,避免使用过于复杂的表达式等。 ...

    pycodestyle原来叫pep8Python编程风格检查程序

    `pycodestyle` 是一款非常重要的Python开发工具,它的主要功能是对Python源代码进行风格检查,确保代码遵循PEP 8的编码规范。PEP 8是Python社区广泛接受的编码风格指南,旨在提高代码的可读性和一致性。`pycodestyle...

    代码规范及CodeStyle使用

    例如,Google提供了针对Java、Python等多种语言的CodeStyle指南,涵盖了代码格式化、布局、注释等多个方面。此外,一些IDE(如IntelliJ IDEA、Visual Studio Code)和代码编辑器提供了CodeStyle配置选项,可以自动...

    INTRODUCTION TO PYTHON SCRIPTING FOR MAYA ARTISTS.

    PEP 8 provides guidelines for Python code style, including naming conventions and whitespace usage. - **PEP 8 Quick Notes:** PEP 8 recommends using lowercase with underscores (snake_case) for ...

    wemake-python-styleguide:有史以来最严格,最自以为是的python linter!

    wemake-python-styleguide 欢迎使用有史以来最严格,最有主见的python linter。 wemake-python-styleguide实际上是一个插件,带有作为依赖项。快速开始pip install wemake-python-styleguide 您还需要使用创建setup....

    Google+Python+Style+Guide中文版

    Google Python 风格指南是一份详细的编程风格规范文档,旨在提供一套标准的代码编写规则,使得代码更加规范和易于阅读。这份指南涉及多个方面,包括但不限于代码风格、注释、类和模块的使用、字符串处理、导入格式、...

    Python编程规范PEP8.pdf

    它的全称是“Style Guide for Python Code”,旨在提升Python代码的可读性和一致性。PEP8最初由Python的创始人Guido van Rossum、Barry Warsaw和Nick Coghlan共同撰写,并随着Python语言的发展不断更新。尽管它主要...

    python pep8编码规范

    PEP 8,全称为“Python Code Style Guide”,是Python官方推荐的编程规范指南。它由Python之父Guido van Rossum与其他开发者共同制定,并于2001年7月5日首次发布。PEP 8的目标在于提供一套统一的代码格式标准,使...

    idea-codestyle-hook-plugin,intellij插件在提交时应用代码样式.zip

    "idea-codestyle-hook-plugin"正是一款专为解决此问题而设计的开源插件,它可以在提交代码时自动应用项目所设定的代码样式,确保每一行代码都符合团队规范。 首先,让我们理解一下代码样式的重要性。代码样式是编程...

    Python PEP8 编码规范中文版.pdf

    Google Python PEP8 编码规范中文版,高清,带书签。 本项目并非 Google 官方项目, 而是由国内程序员凭热情创建和维护。 如果你关注的是 Google 官方英文版, 请移步 Google Style Guide

    Coding Games in Python

    A visual step-by-step guide to writing code in Python. Beginners and experienced programmers can use Python to build and play computer games, from mind-bending brainteasers to crazy action games with ...

    Python库 | cpp_code_style_formatter-1.0.1-py3-none-any.whl

    资源分类:Python库 所属语言:Python 使用前提:需要解压 资源全名:cpp_code_style_formatter-1.0.1-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059

    Pro Python 2nd edition 英文pdf

    Pro Python 第2版,2014....12. Style Guide for Python 13. Voting Guidelines 14. The Zen of Python 15. Docstring Conventions 16. Backward Compatibility Policy 17. Python 3000 18. Python Language Moratorium

    Core PYTHON Programming, 2nd Edition (epub 格式, Python 2.5)

    Using practical code examples, Chun introduces all the fundamentals of Python programming: syntax, objects and memory management, data types, operators, files and I/O, functions, generators, error ...

    Python Machine Learning

    Learn how to build neural networks using Keras and Theano, Find out how to write clean and elegant Python code that will optimize the strength of your algorithms, Discover how to embed your machine ...

    Modular Programming with Python

    • Learn how to use GitHub and the Python Package Index to share your code with other people • Make use of modules and packages that others have written • Use modular techniques to build robust ...

    Python编程规范

    原文“PEP 008 《Style Guide for Python Code》”:http://www.python.org/dev/peps/pep-0008/ 精巧地址:http://bit.ly/2OQ8Z3 其中文翻译:http://wiki.woodpecker.org.cn/moin/PythonCodingRule 精巧地址:...

    Serious Python

    An indispensable collection of practical tips and real-world advice for tackling common Python problems and taking your code to the next level. Features interviews with high-profile Python developers ...

Global site tag (gtag.js) - Google Analytics