標籤:

Python 編碼習慣(Coding Conventions)

轉載來自brd4.braude.ac.il/~samy

James Madison University Python Coding Conventions

By Nathan Sprague

We will follow the PEP 8 Style Guide for Python Code .

This is the style guide that describes the coding standards for code to

be included in the Python standard library.

I encourage you to read that entire document,

but you are only responsible for the boxed (and edited)

excerpts included on this page.

I also recommend taking a look at Google Python Style Guide . Again,

you are not responsible for that material,

but it has some good advice for writing well organized Python code.

Code lay-out

Executable programs for this course should define a main function

that is called from within a conditional block like the following:

if __name__ == "__main__":n main()n

Under no circumstances should your modules include function calls that occur unconditionally. Such calls interfere with the use of PyDoc,

and make it difficult for me to use testing code that imports your module.PEP 8:

IndentationnnUse 4 spaces per indentation level.nnTabs or Spaces?nn Never mix tabs and spaces!nn For new projects, spaces-only are strongly recommended over tabs!n Most editors have features that make this easy to do.n Best practice: avoid tabs at all!nnMaximum Line Lengthnn Limit all lines to a maximum of 79 characters.nn The preferred way of wrapping long lines is by using Pythons implied linen continuation inside parentheses, brackets and braces. Long lines can ben broken over multiple lines by wrapping expressions in parentheses. Thesen should be used in preference to using a backslash for line continuation.n Make sure to indent the continued line appropriately. The preferred placen to break around a binary operator is *after* the operator, not before it.n Some examples:nnclass Rectangle(Blob):nn def __init__(self, width, height,n color=black, emphasis=None, highlight=0):n if (width == 0 and height == 0 andn color == red and emphasis == strong orn highlight > 100):n raise ValueError("sorry, you lose")n if width == 0 and height == 0 and (color == red orn emphasis is None):n raise ValueError("I dont think so -- values are %s, %s" %n (width, height))n Blob.__init__(self, width, height,n color, emphasis, highlight)n

Imports

PEP 8:

- Imports should usually be on separate lines, e.g.:nn Yes: import osn import sysnn No: import sys, osnn its okay to say this though:nn from subprocess import Popen, PIPEnn - Imports are always put at the top of the file, just after any modulen comments and docstrings, and before module globals and constants.n

Whitespace in Expressions and Statements

PEP 8:

Avoid extraneous whitespace in the following situations:nn - Immediately inside parentheses, brackets or braces.nn Yes: spam(ham[1], {eggs: 2})n No: spam( ham[ 1 ], { eggs: 2 } )nn - Immediately before a comma, semicolon, or colon:nn Yes: if x == 4: print x, y; x, y = y, xn No: if x == 4 : print x , y ; x , y = y , xnn - Immediately before the open parenthesis that starts the argumentn list of a function call:nn Yes: spam(1)n No: spam (1)nn - Immediately before the open parenthesis that starts an indexing orn slicing:nn Yes: dict[key] = list[index]n No: dict [key] = list [index]nn - More than one space around an assignment (or other) operator ton align it with another.nn Yes:nn x = 1n y = 2n long_variable = 3nn No:nn x = 1n y = 2n long_variable = 3nnn Other Recommendationsnn - Always surround these binary operators with a single space onn either side: assignment (=), augmented assignment (+=, -= etc.),n comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not),n Booleans (and, or, not).nn - Use spaces around arithmetic operators:nn Yes:nn i = i + 1n submitted += 1n x = x * 2 - 1n hypot2 = x * x + y * yn c = (a + b) * (a - b)nn No:nn i=i+1n submitted +=1n x = x*2 - 1n hypot2 = x*x + y*yn c = (a+b) * (a-b)nn - Dont use spaces around the = sign when used to indicate an keyword argument or a default parameter value.nn Yes:nn def complex(real, imag=0.0):n return magic(r=real, i=imag)nn No:nn def complex(real, imag = 0.0):n return magic(r = real, i = imag)nn - Compound statements (multiple statements on the same line) aren generally discouraged.nn Yes:nn if foo == blah:n do_blah_thing()n do_one()n do_two()n do_three()nn Rather not:nn if foo == blah: do_blah_thing()n do_one(); do_two(); do_three()nn - While sometimes its okay to put an if/for/while with a smalln body on the same line, never do this for multi-clausen statements. Also avoid folding such long lines!nn Rather not:nn if foo == blah: do_blah_thing()n for x in lst: total += xn while t < 10: t = delay()nn Definitely not:nn if foo == blah: do_blah_thing()n else: do_non_blah_thing()nn try: something()n finally: cleanup()nn do_one(); do_two(); do_three(long, argument,n list, like, this)nn if foo == blah: one(); two(); three()n

Comments

The point of comments is to clarify code that might otherwise be difficult for the reader to follow. Well organized Python code with informative variable names should require very few comments inside the bodies of functions and methods.

PEP 8:

Comments that contradict the code are worse than no comments. Always maken a priority of keeping the comments up-to-date when the code changes!nn Comments should be complete sentences. If a comment is a phrase orn sentence, its first word should be capitalized, unless it is an identifiern that begins with a lower case letter (never alter the case ofn identifiers!).nn If a comment is short, the period at the end can be omitted. Blockn comments generally consist of one or more paragraphs built out of completen sentences, and each sentence should end in a period.nn You should use two spaces after a sentence-ending period.nn When writing English, Strunk and White apply.nnn Block Commentsnn Block comments generally apply to some (or all) code that follows them,n and are indented to the same level as that code. Each line of a blockn comment starts with a # and a single space (unless it is indented textn inside the comment).n n Paragraphs inside a block comment are separated by a line containing an single #.nn Inline Commentsnn Use inline comments sparingly.n n An inline comment is a comment on the same line as a statement. Inlinen comments should be separated by at least two spaces from the statement.n They should start with a # and a single space.n n Inline comments are unnecessary and in fact distracting if they staten the obvious. Dont do this:n n x = x + 1 # Increment xn n But sometimes, this is useful:n n x = x + 1 # Compensate for bordern

Documentation Strings

PEP 8:

Conventions for writing good documentation strings (a.k.a. "docstrings")n are immortalized in PEP 257 [3].nn - Write docstrings for all public modules, functions, classes, andn methods. Docstrings are not necessary for non-public methods, but youn should have a comment that describes what the method does. This commentn should appear after the "def" line.nn - PEP 257 describes good docstring conventions. Note that mostn importantly, the """ that ends a multiline docstring should be on a linen by itself, and preferably preceded by a blank line, e.g.:nn """Return a foobangnn Optional plotz says to frobnicate the bizbaz first.nn """nn - For one liner docstrings, its okay to keep the closing """ on the samen line.n

Module headers should include a brief description of the module as well as author and version information. A separate block comment should include your honor code statement.

Naming Conventions

Selecting informative names is one of the most important steps in writing readable, maintainable, and correct code. Variable names should generally be nouns, and should clearly describe what the variable is intended to contain. Single letter variable are almost never acceptable, with exception of loop index variables. It is usually a good idea to use plural nouns for variables that will contain collections, and singular nouns for variables that will contain individual objects.

Variable names should balance clarity with brevity. The name person is better than currentPersonObject. However, per is worse than either (percentage? person?, permitted?).

Function and method names should typically be verbs and should describe what the function or method is intended to accomplish.

Avoid selecting place-holder names with the intention of replacing them later. If you arent sure what the variable or function should be named, thats often an indication that you dont have a clear idea of what the variable will hold or what the function should accomplish. Taking the time to figure out an appropriate name will clarify your thinking.

PEP 8 (CS240 changes in red):

Comments that contradict the code are worse than no comments. Always maken a priority of keeping the comments up-to-date when the code changes!nn Comments should be complete sentences. If a comment is a phrase orn sentence, its first word should be capitalized, unless it is an identifiern that begins with a lower case letter (never alter the case ofn identifiers!).nn If a comment is short, the period at the end can be omitted. Blockn comments generally consist of one or more paragraphs built out of completen sentences, and each sentence should end in a period.nn You should use two spaces after a sentence-ending period.nn When writing English, Strunk and White apply.nnnBlock Commentsnn Block comments generally apply to some (or all) code that follows them,n and are indented to the same level as that code. Each line of a blockn comment starts with a # and a single space (unless it is indented textn inside the comment).nn Paragraphs inside a block comment are separated by a line containing an single #.nnInline Commentsnn Use inline comments sparingly.nn An inline comment is a comment on the same line as a statement. Inlinen comments should be separated by at least two spaces from the statement.n They should start with a # and a single space.nn Inline comments are unnecessary and in fact distracting if they staten the obvious. Dont do this:nn x = x + 1 # Increment xnn But sometimes, this is useful:nn x = x + 1 # Compensate for bordern

Programming Recommendations

PEP 8:

n - Dont compare boolean values to True or False using ==nn Yes: if greeting:n n No: if greeting == True:n n Worse: if greeting is True:n

推薦閱讀:

TAG:Python |