没有合适的资源?快使用搜索试试~ 我知道了~
google的python编码规范.pdf
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 108 浏览量
2021-12-03
21:22:03
上传
评论
收藏 252KB PDF 举报
温馨提示
试读
24页
google的python编码规范.pdf
资源推荐
资源详情
资源评论
Google Python Style Guide
Revision 2.19
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 PackagesExceptions Global variables Nested/Local/Inner Classes and
FunctionsList Comprehensions Default Iterators and Operators Generators Lambda
FunctionsDefault Argument Values Properties True/False evaluations Deprecated
Language FeaturesLexical Scoping Function and Method Decorators Threading Power
Features
Python
Style Rules
Semicolons Line length Parentheses Indentation Blank Lines Whitespace Python
InterpreterComments Classes Strings TODO Comments Imports
formatting Statements Access Control NamingMain
Important Note
Displaying Hidden Details in this Guide
link ▽
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 do s and don't s
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.
Python Language Rules
pychecker
link ▽
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) = (d, e) # Silence pychecker
return a
Ideally, pychecker would be extended to ensure that such `unused declarations' were true.
Imports
link ▽
Use import s 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.
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 z 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.
Packages
link ▽
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
Exceptions
link ▽
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.
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.
Global variables
link ▽
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.
Nested/Local/Inner Classes and Functions
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.
List Comprehensions
link ▽
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.
No:
result = [(x, y) for x in range(10) for y in range(5) if x * y > 10]
return ((x, y, z)
for x in xrange(5)
for y in xrange(5)
if x != y
for z in xrange(5)
if y != z)
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:
剩余23页未读,继续阅读
资源评论
BlueWatergg
- 粉丝: 3
- 资源: 11万+
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功