首页 > > > Python 代码规范
点击关注上方“SQL数据库开发”,
设为“置顶或星标”,第一时间送达干货

如无特殊情况, 文件一律使用 UTF-8 编码
如无特殊情况, 文件头部必须加入#-*-coding:utf-8-*-标识
统一使用 4 个空格进行缩进
每行代码尽量不超过 80 个字符(在特殊情况下可以略微超过 80 ,但最长不得超过 120)
理由:
这在查看 side-by-side 的 diff 时很有帮助
方便在控制台下查看代码
太长可能是设计有缺陷
简单说,自然语言使用双引号,机器标示使用单引号,因此 代码里 多数应该使用 单引号
自然语言 使用双引号 "..."
例如错误信息;很多情况还是 unicode,使用u"你好世界"
机器标识 使用单引号 '...'
例如 dict 里的 key
正则表达式 使用原生的双引号 r"..."
文档字符串 (docstring) 使用三个双引号 """......"""
模块级函数和类定义之间空两行;
类成员函数之间空一行;
class A:
def __init__(self):
pass
def hello(self):
pass
def main():
pass
可以使用多个空行分隔多组相关的函数
函数中可以使用空行分隔出逻辑相关的代码
文件使用 UTF-8 编码
文件头部加入#-*-conding:utf-8-*-标识
import 语句应该分行书写
# 正确的写法
import os
import sys
# 不推荐的写法
import sys,os
# 正确的写法
from subprocess import Popen, PIPE复制代码
import语句应该使用 absolute import
# 正确的写法
from foo.bar import Bar
# 不推荐的写法
from ..bar import Bar
import语句应该放在文件头部,置于模块说明及docstring之后,于全局变量之前;
import语句应该按照顺序排列,每组之间用一个空行分隔
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 支持括号内的换行。这时有两种情况。
1) 第二行缩进到括号的起始处
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()
"""Return a foobar
Optional plotz says to frobnicate the bizbaz first.
"""
"""Oneline docstring"""
# 块注释
# 块注释
#
# 块注释
# 块注释
# 正确的写法
x = x + 1 # 边框加粗一个像素
# 不推荐的写法(无意义的注释)
x = x + 1 # x加1
app = create_app(name, options)
# =====================================
# 请勿在此处添加 get post等app路由行为 !!!
# =====================================
if __name__ == '__main__':
app.run()
# -*- coding: utf-8 -*-
"""Example docstrings.
This module demonstrates documentation as specified by the `Google Python
Style Guide`_. Docstrings may extend over multiple lines. Sections are created
with a section header and a colon followed by a block of indented text.
Example:
Examples can be given using either the ``Example`` or ``Examples``
sections. Sections support any reStructuredText formatting, including
literal blocks::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime a new section starts.
"""
# 不推荐的写法(不要写函数原型等废话)
def function(a, b):
"""function(a, b) -> list"""
... ...
# 正确的写法
def function(a, b):
"""计算并返回a到b范围内数据的平均值"""
... ...
def func(arg1, arg2):
"""在这里写函数的一句话总结(如: 计算平均值).
这里是具体描述.
参数
----------
arg1 : int
arg1的具体描述
arg2 : int
arg2的具体描述
返回值
-------
int
返回值的具体描述
参看
--------
otherfunc : 其它关联函数等...
示例
--------
示例使用doctest格式, 在`>>>`后的代码可以被文档测试工具作为测试用例自动运行
>>> a=[1,2,3]
>>> print [x + 3 for x in a]
[4, 5, 6]
"""
# 正确的模块名
import decoder
import html_parser
# 不推荐的模块名
import Decoder
class Farm():
pass
class AnimalFarm(Farm):
pass
class _PrivateFarm(Farm):
pass
def run():
pass
def run_with_env():
pass复制代码
私有函数在函数前加一个下划线_
class Person():
def _private_func():
pass
if __name__ == '__main__':
count = 0
school_name = ''复制代码
常量采用全大写,如有多个单词,使用下划线隔开
MAX_CLIENT = 100
MAX_CONNECTION = 1000
CONNECTION_TIMEOUT = 600
MAX_OVERFLOW = 100
Class FooBar:
def foo_bar(self, print_):
print(print_)
——End——
后台回复关键字:1024,获取一份精心整理的技术干货
后台回复关键字:进群,带你进入高手如云的交流群。
推荐阅读
点击「阅读原文」了解SQL训练营原文作者:;如有侵权,请联系管理员删除。