Google 为方便大家使用,为 Vim 创建了一个设置文件。 对于 Emacs,默认设置应该可以。许多团队使用yapf自动格式化程序来避免争论格式化问题。
" Indent Python in the Google way.
setlocal indentexpr=GetGooglePythonIndent(v:lnum)
let s:maxoff = 50 " maximum number of lines to look backwards.
function GetGooglePythonIndent(lnum)
" Indent inside parens.
" Align with the open paren unless it is at the end of the line.
" E.g.
" open_paren_not_at_EOL(100,
" (200,
" 300),
" 400)
" open_paren_at_EOL(
" 100, 200, 300, 400)
call cursor(a:lnum, 1)
let [par_line, par_col] = searchpairpos('(\|{\|\[', '', ')\|}\|\]', 'bW',
\ "line('.') < " . (a:lnum - s:maxoff) . " ? dummy :"
\ . " synIDattr(synID(line('.'), col('.'), 1), 'name')"
\ . " =~ '\\(Comment\\|String\\)$'")
if par_line > 0
call cursor(par_line, 1)
if par_col != col("$") - 1
return par_col
endif
endif
" Delegate the rest to the original function.
return GetPythonIndent(a:lnum)
endfunction
let pyindent_nested_paren="&sw*2"
let pyindent_open_paren="&sw*2"
每行代码尽量不超过 80 个字符 (在特殊情况下可以略微超过 80 ,但最长不得超过 120) 理由:
简单说,自然语言使用双引号,机器标示使用单引号,因此 代码里 多数应该使用 单引号
"..."u"你好世界"'...' 例如 dict 里的 keyr"...""""......"""
class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass
#-*-coding:utf-8-*- 标识# 正确的写法 import os import sys # 不推荐的写法 import sys,os # 正确的写法 from subprocess import Popen, PIPE
# 正确的写法 from foo.bar import Bar # 不推荐的写法 from ..bar import Bar
import os import sys import msgpack import zmq import foo
from myclass import MyClass
import bar import foo.bar bar.Bar() foo.bar.Bar()
[=,-,+=,==,>,in,is not, and]:# 正确的写法 i = i + 1 submitted += 1 x = x * 2 - 1 hypot2 = x * x + y * y c = (a + b) * (a - b) # 不推荐的写法 i=i+1 submitted +=1 x = x*2 - 1 hypot2 = x*x + y*y c = (a+b) * (a-b)
# 正确的写法
def complex(real, imag):
pass
# 不推荐的写法
def complex(real,imag):
pass
# 正确的写法
def complex(real, imag=0.0):
pass
# 不推荐的写法
def complex(real, imag = 0.0):
pass
# 正确的写法
spam(ham[1], {eggs: 2})
# 不推荐的写法
spam( ham[1], { eggs : 2 } )
# 正确的写法 dict['key'] = list[index] # 不推荐的写法 dict ['key'] = list [index]
# 正确的写法 x = 1 y = 2 long_variable = 3 # 不推荐的写法 x = 1 y = 2 long_variable = 3
Python 支持括号内的换行。这时有两种情况。
foo = long_function_name(var_one, var_two,
var_three, var_four)
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
session.query(MyTable).\
filter_by(id=1).\
one()
print 'Hello, '\
'%s %s!' %\
('Harry', 'Potter')
# 正确的写法 do_first() do_second() do_third() # 不推荐的写法 do_first();do_second();do_third();
if/for/while 一定要换行:
# 正确的写法
if foo == 'blah':
do_blah_thing()
# 不推荐的写法
if foo == 'blah': do_blash_thing()
docstring 的规范中最其本的两点:
"""Return a foobar Optional plotz says to frobnicate the bizbaz first. """ """Oneline docstring"""