没有合适的资源?快使用搜索试试~ 我知道了~
首页google python 编程规范
google python 编程规范
4星 · 超过85%的资源 需积分: 10 6 下载量 195 浏览量
更新于2023-06-04
评论 1
收藏 359KB PDF 举报
Python is the main scripting language used at Google. This style guide is a list of dos and don'ts for Python programs. To help you format code correctly, we've created a settings file for Vim. For Emacs, the default settings should be fine. from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's a "toggle all" at the t
资源详情
资源评论
资源推荐
link
▽
Google Python Style Guide
Revision 2.39
Amit Patel
Antoine Picard
Eugene Jhong
Jeremy Hylton
Matt Smart
Mike Shields
Each style point has a summary for which
additional information is available by
toggling the accompanying arrow button
that looks this way: ▽ . You may toggle
all summaries with the big arrow button:
▽ Toggle all summaries
Table of Contents
Python
Language
Rules
pychecker Imports Packages Exceptions
Global variables
Nested/Local/Inner Classes and Functions
List Comprehensions Default Iterators and Operators
Generators Lambda Functions
Conditional Expressions Default Argument Values
Properties True/False evaluations
Deprecated Language Features Lexical Scoping
Function and Method Decorators Threading
Power Features
Python
Style
Rules
Semicolons Line length Parentheses Indentation
Blank Lines Whitespace Shebang Line Comments
Classes Strings Files and Sockets TODO Comments
Imports formatting Statements Access Control
Naming Main
Important Note
Di sp la yi ng H id de n De ta il s in t hi s Gu id e
This style guide contains many details that are initially hidden
from view. They are marked by the triangle icon, which you see here
on your left. Click it now. You should see "Hooray" appear below.
Hooray! Now you know you can expand points to get more details.
Alternatively, there's a "toggle all" at the top of this document.
Background
Python is the main scripting language used at Google. This style guide
is a list of dos and don'ts for Python programs.
To help you format code correctly, we've created a settings file for
Vim. For Emacs, the default settings should be fine.
link
▽
link
▽
Python Language Rules
py ch ec ke r
Run pychecker over your code.
Definition:
PyChecker is a tool for finding bugs in Python source code. It finds
problems that are typically caught by a compiler for less dynamic
languages like C and C++. It is similar to lint. Because of the dynamic
nature of Python, some warnings may be incorrect; however, spurious
warnings should be fairly infrequent.
Pros:
Catches easy-to-miss errors like typos, use-vars-before-assignment, etc.
Cons:
pychecker isn't perfect. To take advantage of it, we'll need to
sometimes: a) Write around it b) Suppress its warnings c) Improve it or
d) Ignore it.
Decision:
Make sure you run pychecker on your code.
For information on how to run pychecker, see the pychecker homepage
To suppress warnings, you can set a module-level variable named
__pychecker__ to suppress appropriate warnings. For example:
__pychecker__ = 'no-callinit no-classattr'
Suppressing in this way has the advantage that we can easily search for
suppressions and revisit them.
You can get a list of pychecker warnings by doing pychecker --help.
Unused argument warnings can be suppressed by using `_' as the
identifier for the unused argument or prefixing the argument name with
`unused_'. In situations where changing the argument names is
infeasible, you can mention them at the beginning of the function. For
example:
def foo(a, unused_b, unused_c, d=None, e=None):
_ = d, e
return a
Ideally, pychecker would be extended to ensure that such `unused
declarations' were true.
Im po rt s
Use imports for packages and modules only.
Definition:
Reusability mechanism for sharing code from one module to another.
Pros:
The namespace management convention is simple. The source of each
identifier is indicated in a consistent way; x.Obj says that object Obj
is defined in module x.
link
▽
link
▽
Cons:
Module names can still collide. Some module names are inconveniently
long.
Decision:
Use import x for importing packages and modules.
Use from x import y where x is the package prefix and y is the module
name with no prefix.
Use from x import y as z if two modules named y are to be imported or if
y is an inconveniently long name.
For example the module sound.effects.echo may be imported as follows:
from sound.effects import echo
...
echo.EchoFilter(input, output, delay=0.7, atten=4)
Do not use relative names in imports. Even if the module is in the same
package, use the full package name. This helps prevent unintentionally
importing a package twice.
Pa ck ag es
Import each module using the full pathname location of the module.
Pros:
Avoids conflicts in module names. Makes it easier to find modules.
Cons:
Makes it harder to deploy code because you have to replicate the package
hierarchy.
Decision:
All new code should import each module by its full package name.
Imports should be as follows:
# Reference in code with complete name.
import sound.effects.echo
# Reference in code with just module name (preferred).
from sound.effects import echo
Ex ce pt io ns
Exceptions are allowed but must be used carefully.
Definition:
Exceptions are a means of breaking out of the normal flow of control of
a code block to handle errors or other exceptional conditions.
Pros:
The control flow of normal operation code is not cluttered by error-
handling code. It also allows the control flow to skip multiple frames
when a certain condition occurs, e.g., returning from N nested functions
in one step instead of having to carry-through error codes.
Cons:
May cause the control flow to be confusing. Easy to miss error cases
when making library calls.
link
▽
Decision:
Exceptions must follow certain conditions:
Raise exceptions like this: raise MyException('Error message') or
raise MyException. Do not use the two-argument form (raise
MyException, 'Error message') or deprecated string-based
exceptions (raise 'Error message').
Modules or packages should define their own domain-specific base
exception class, which should inherit from the built-in Exception
class. The base exception for a module should be called Error.
class Error(Exception):
pass
Never use catch-all except: statements, or catch Exception or
StandardError, unless you are re-raising the exception or in the
outermost block in your thread (and printing an error message).
Python is very tolerant in this regard and except: will really
catch everything including Python syntax errors. It is easy to
hide real bugs using except:.
Minimize the amount of code in a try/except block. The larger the
body of the try, the more likely that an exception will be raised
by a line of code that you didn't expect to raise an exception. In
those cases, the try/except block hides a real error.
Use the finally clause to execute code whether or not an exception
is raised in the try block. This is often useful for cleanup,
i.e., closing a file.
When capturing an exception, use as rather than a comma. For
example:
try:
raise Error
except Error as error:
pass
Gl ob al v ar ia bl es
Avoid global variables.
Definition:
Variables that are declared at the module level.
Pros:
Occasionally useful.
Cons:
Has the potential to change module behavior during the import, because
assignments to module-level variables are done when the module is
imported.
Decision:
Avoid global variables in favor of class variables. Some exceptions are:
Default options for scripts.
Module-level constants. For example: PI = 3.14159. Constants
should be named using all caps with underscores; see Naming below.
It is sometimes useful for globals to cache values needed or
returned by functions.
If needed, globals should be made internal to the module and
accessed through public module level functions; see Naming below.
Ne st ed /L oc al /I nn er C la ss es a nd F un ct io ns
link
▽
link
▽
Nested/local/inner classes and functions are fine.
Definition:
A class can be defined inside of a method, function, or class. A
function can be defined inside a method or function. Nested functions
have read-only access to variables defined in enclosing scopes.
Pros:
Allows definition of utility classes and functions that are only used
inside of a very limited scope. Very ADT-y.
Cons:
Instances of nested or local classes cannot be pickled.
Decision:
They are fine.
Li st C om pr eh en si on s
Okay to use for simple cases.
Definition:
List comprehensions and generator expressions provide a concise and
efficient way to create lists and iterators without resorting to the use
of map(), filter(), or lambda.
Pros:
Simple list comprehensions can be clearer and simpler than other list
creation techniques. Generator expressions can be very efficient, since
they avoid the creation of a list entirely.
Cons:
Complicated list comprehensions or generator expressions can be hard to
read.
Decision:
Okay to use for simple cases. Each portion must fit on one line: mapping
expression, for clause, filter expression. Multiple for clauses or
filter expressions are not permitted. Use loops instead when things get
more complicated.
Yes:
result = []
for x in range(10):
for y in range(5):
if x * y > 10:
result.append((x, y))
for x in xrange(5):
for y in xrange(5):
if x != y:
for z in xrange(5):
if y != z:
yield (x, y, z)
return ((x, complicated_transform(x))
for x in long_generator_function(parameter)
if x is not None)
squares = [x * x for x in range(10)]
eat(jelly_bean for jelly_bean in jelly_beans
剩余22页未读,继续阅读
fishX
- 粉丝: 0
- 资源: 2
上传资源 快速赚钱
- 我的内容管理 收起
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
会员权益专享
最新资源
- zigbee-cluster-library-specification
- JSBSim Reference Manual
- c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf
- 建筑供配电系统相关课件.pptx
- 企业管理规章制度及管理模式.doc
- vb打开摄像头.doc
- 云计算-可信计算中认证协议改进方案.pdf
- [详细完整版]单片机编程4.ppt
- c语言常用算法.pdf
- c++经典程序代码大全.pdf
- 单片机数字时钟资料.doc
- 11项目管理前沿1.0.pptx
- 基于ssm的“魅力”繁峙宣传网站的设计与实现论文.doc
- 智慧交通综合解决方案.pptx
- 建筑防潮设计-PowerPointPresentati.pptx
- SPC统计过程控制程序.pptx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论1