Python Style Specification

Source: Internet
Author: User

semicolonDo not add semicolons at the end of the line, and do not use semicolons to place two commands on the same row. length of the President no more than 80 characters per lineException: If you use Python version 2.4 or earlier, the imported module may have more than 80 characters in the row. Python can use this feature by implicitly connecting parentheses, brackets, and lines in braces. If you want, you can add an extra pair of parentheses around the outside of an expression. Yes:foo_bar (self, width, height, color= ' black ', Design=none, x= ' foo ', Emphasis=none, highlight=0) if (width = = 0 and he Ight = = 0 and color = = ' red ' and emphasis = = ' strong '): If a text string does not fit on one line, you can use parentheses to implement an implicit row connection: x = (' This will build a very lo ng Long "long Long Long") Note the element indentation in the example above; You can find explanations in the indentation section of this article. brackets Ningquewulan using parenthesesDo not use parentheses in a return statement or conditional statement unless it is used to implement a row connection. However, it is possible to use parentheses on either side of the tuple. Yes:if Foo:bar () while x:x = Bar () if X and Y:bar () if not X:bar () return foofor (x, y) in Dict.items (): ... No:if (x): bar () if not (x): Bar () return (foo)Indent in indent code with 4 spacesNever use tab and do not mix tabs and spaces. For a row connection, you should either align the wrapped element vertically (see example of the line length section) or use a 4-space hanging indent (at which point the first line should not have parameters): Yes: # Aligned with opening Delimiterfoo = Long_functio N_name (Var_one, Var_two,var_three, var_four) # 4-space hanging indent; Nothing on First linefoo = Long_function_name (Var_one, Var_two, Var_three,var_four) No.: # Stuff on first line Forbiddenfoo = Long_function_name (Var_one, Var_two,var_three, var_four) # 2-space hanging indent Forbiddenfoo = Long_function_name ( Var_one, Var_two, Var_three,var_four)Blank Line the top-level definition is empty between two lines, the method defines an empty line betweenThere are two empty rows between the top-level definitions, such as functions or class definitions. method definition, the class definition and the first method should be empty lines. In a function or method, there is a blank line in some places if you feel fit.Space use spaces on both sides of punctuation according to standard typographic specifications1. Do not include spaces in parentheses. Yes: spam (ham[1], {eggs: 2}, []) no: spam ( ham[ 1 ], { eggs:  2 }, [ ] )  2. Do not precede commas, semicolons, and colons with spaces, but should be appended to them (except at the end of the line). yes: if x == 4:print x, yx, y = y, xno: if x  == 4 :p rint x , yx , y = y , x 3. argument list, no spaces should be added before the opening parenthesis of an index or slice. Yes: spam (1) yes: spam  (1) yes: dict[' key '] = list[index]no: dict [' key ' ] = list [index] 4. Add a space on both sides of the two-dollar operator, such as assignment (=), Comparison (= =, <,;,! =, <>, <=, >=, in, Notin, was, is not), Boolean (and, or, not). As for how to use the space on either side of the arithmetic operator, you need to judge it yourself. But be sure to keep it consistent on both sides. Yes: x == 1no: x<1 5. When ' = ' is used to indicate a keyword parameter or default parameter value, do not use spaces on either side of it. Yes: def complex (real, imag=0.0):  return magic (R=real, i=imag) No: def  Complex (real, imag = 0.0):  return magic (r  = real, i = imag)  6. Do not use spaces to vertically align multiple lines of markup, as this becomes a burden for maintenance (for:, #, =, etc.): yes:foo = 1000 # commentlong_name = 2  # comment that should not be aligneddictionary = {"foo":  1, "Long_name":  2,}no:foo = 1000 # commentlong_name = 2 # comment  that should not be aligneddictionary = {"foo"  : 1, "long_name":  2,}   Python Interpreter Each module should start with #!/usr/bin/env pythonThe module should start with a construction line to specify the Python interpreter used to execute the program: #!/usr/bin/env python2.4 always uses the most specific version, for example, using/usr/bin/python2.4 instead of/usr/bin/ Python2. This way, when you upgrade to a different Python version, you can easily find dependencies and avoid confusion when you use them. For example, does/usr/bin/python2 represent/usr/bin/python2.0.1 or/usr/bin/python2.3.0? NotesMake sure you use the correct style for modules, functions, methods, and inline annotations Document StringPython has a unique way of commenting: using a document string. A document string is the first statement in a package, module, class, or function. These strings can be automatically extracted through the __DOC__ members of the object and are used by the Pydoc. (You can run Pydoc on your module and try to see what it looks like). Our Convention with document strings is to use triple double quotes. A document string should be organized like this: the first is an overview of a line with a period, a question mark, or an exclamation point. Then there is a blank line. Next is the remainder of the document string, which should be aligned with the first quotation mark of the first line of the document string. The following are the formatting specifications for more document strings. ModuleEach file should contain the following items, followed by: 1. Copyright notice (for example, copyright © Google INC) 72. A license template. Depending on the license used for the project (for example, Apache 2.0, BSD, LGPL, GPL), select the appropriate template 3. The author declares that the original author of the document is identified. functions and methodsIf it is not both obvious and short, any function or method requires a document string. Furthermore, any externally accessible function or method, no matter how short or simple, requires a document string. The document string should contain what the function does, as well as a detailed description of the input and output. In general, you should not describe "what to do" unless it is a complex algorithm. For tricky code, block comments or inline comments are the most important. The document string should provide enough information, and when someone else writes code to call the function, he doesn't need to look at a line of code, just look at the document string. Documents should be written separately for parameters. Follow the colon followed by an explanation, and should be indented with a uniform hanging 2 or 4 space. The document string should specify the desired type where a specific type is required. The "Raise:" section should list any exceptions that the function might trigger. The document string for the generator function should be "yields:" rather than "Returns:". Def fetch_bigtable_rows (Big_table, keys, other_silly_ Variable=none): "" "Fetches rows from a bigtable.retrieves rows pertaining to  the given keys from the table instancerepresented by big_table.  silly things may happen ifother_silly_variable is not none.args:big_ table: an open bigtable table instance.keys: a sequence of  Strings representing the key of each table rowto fetch.other_silly_ Variable: another optional variable, that has a muchlonger name than the other args, and  Which does nothing. returns:a dict mapping keys to the corresponding table row  datafetched. each row is represented as a tuple of strings.  forexample:{' Serak ':  (' rigel vii ',  ' preparer '), ' Zim ':  (' Irk ',  ' Invader '), ' lrrr ':   (' omicron persei 8 ',  ' Emperor ')}if a key from the keys  Argument is missing from the dictionary,then that row was not  found in the table. Raises:ioerror: an error occurred accessing the bigtable. Table object. "" " pass  class? The class should have a document string that describes the class under its definition. If your class has public properties (Attributes), then there should be an attribute (Attributes) segment in the document. And you should follow the same format as the function parameter. Class SampleClass (object): "" "Summary of Class Here. Longer class information .... Longer class information .... Attributes:likes_spam:a Boolean indicating if we like spam or not.eggs:An integer count of the eggs we have laid. "" def __init__ (self, Likes_spam=false): "" "Inits sampleclass with blah." " Self.likes_spam = Likes_spamself.eggs = 0def Public_method (self): "" "performs operation blah." " block comments and line comments? The most need to write comments is the tricky parts of the code. If you have to explain the next code walk, you should write it now. For complex operations, you should write several lines of comments before their operations begin. For code that is not at a glance, you should add a comment at the end of its line. # We use a weighted dictionary search for find out where I am in# the array. We extrapolate position based on the largest num# in the array with the array size and then do binary search to# get the EX Act Number.if I & (i-1) = = 0: # True IFF I is a power of 2 for readability, comments should leave at least 2 spaces in code. On the other hand, never describe the code. Suppose the person reading the code knows more about Python than you do, he just doesn't know what your code is going to do. # bad Comment:now go through the B array and make sure whenever I occurs# the next ele ment is i+1 class? If a class does not inherit from another class, it is explicitly inherited from object. The same is true for nested classes. No:class sampleclass:passclass outerclass:class InnerClass:passYes:class sampleclass (object):p Assclass Outerclass ( Object): Class Innerclass (object):p Assclass childclass (parentclass): "" "explicitly inherits from another class already." " Inherited from object is for the properties to work properly, and this protects your code from a special potential incompatibility with Python 3000. This also defines special methods that implement the object's default semantics, including __new__, __init__, __delattr__, __getattribute__,__setattr__, __hash__, __repr__, and __str__. string? Format the string with the% operator, even if the argument is a string. But you can't generalize, you need to judge between + and% well. no: x =  '%s%s '  %  (a, b)  # use + in this casex  = imperative +  ',  '  + expletive +  '! ' x =  ' name:  '  + name +  '; score:  '  + str (n) yes: x  = a + bx =  '%s, %s! '  %  (imperative, expletive) x =  ' name: %s; score: %d '  %  (name,  n)   Avoid accumulating strings with the + and + = operators in the loop. Because the string is immutable, doing so creates unnecessary temporary objects and results in a two-time rather than linear run time. As an alternative, you can add each substring to the list and then use the. Join connection list after the loop ends. (You can also write each substring to a cstringio.stringio cache.) no: employee_table =  ' <table> ' for last_name, first_name in employee_ list:employee_table +=  ' <tr><td>%s, %s</td></tr> '  %  (last_ Name, first_name) employee_table +=  ' </table> ' yes: items = [' &LT;TABLE&Gt; '] For last_name, first_name in employee_list:items.append (' <tr><td>%s, %s </td></tr> '  %  (last_name, first_name) items.append (' </table> ') employee_table  =  ". Join (items) uses triple double quotes instead of triple single quotes for multiline strings. Note, however, that implicit row joins are usually clearer, because multiline strings do not conform to the indentation of other parts of the program. no:print  "" "this is pretty ugly. Don ' T do this. "" " yes:print  ("this is much nicer.\n" "do it this way.\n")   TODO Comments? Use TODO comments for temporary code, which is a short-term solution. It's not perfect, but it's good enough. Todo comments should include a "todo" string at all the beginning, followed by your name, email address, or other identifier enclosed in parentheses. Then an optional colon. Then there must be a line of comments explaining what to do. The main purpose is to have a unified todo format so that people who add comments can search (and can provide more details as needed). Writing a TODO comment does not guarantee that the person who wrote it will solve the problem personally. # todo ([email protected]): Drop the use of "Has_key". # todo (Zeke) change this to use relations. If you Todo is the "do something in the future" form, then make sure you include a specified date ("November 2009 fix") or a specific event ("Remove the code until all customers can process the XML request"). Import Format? Each import should have a single row yes:import osimport sysno:import OS, the SYS import should always be placed at the top of the file, after the module comments and document strings, before the module global variables and constants. The import should be grouped in the order from most general to least common: 1. Standard library Import 2. Third-party library import 3. The application specifies that each grouping should be imported, and should be sorted in dictionary order based on the full package path of each module, ignoring case. import foofrom foo import barfrom foo.bar import bazfrom foo.bar import Quuxfro M Foob Import ar Statement? Usually each statement should have a single row however, if the test results and test statements are placed on one line, you can also put them on the same line. If this is an if statement, you can do so only if there is no else. In particular, never do this to try/except, because try and except cannot be placed on the same line. Yes:if Foo:bar (foo) no:if Foo:bar (foo) else:baz (foo) try:bar (foo) except Valueerror:baz (foo) 12try:bar (foo) except Valueerror:baz (foo) Access Control? In Python, for trivial and less important access functions, you should replace them directly with public variables, which avoids the overhead of additional function calls. When adding more features, you can use attributes to keep the syntax consistent. (Translator note: Attaching importance to encapsulation object-oriented programmers see this may be very objectionable because they have been educated: all member variables must be private! Actually, that's a bit of a hassle. Try to accept pythonic philosophy. On the other hand, if the access is more complex, or the access cost of the variable is significant, Then you should use a function call such as Get_foo () and Set_foo (). If the previous code behavior allows access through the property, do not bind the new Access function to the property. In this way, any code that attempts to access the variable through the old method will not work, and the user will realize that the complexity has changed. namingModule_name, package_name,classname, method_name, exceptionname, function_name,global_var_ Name,instance_var_name, function_parameter_name, local_var_name. Name 1 that should be avoided. Single-letter name, in addition to counters and iterators. 2. Hyphen (-) 3 in the Package/module name. A double underscore begins with the name (Python retains, for example, __init__) naming convention 1. The so-called "internal (Internal)" means that only the module is available, or, within the class, is protected or private. 2. Starting with a single underscore (_) indicates that a module variable or function is protected (not included when using import * from). 3. An instance variable or method that begins with a double underscore (__) represents a private in-class. 4. Place related classes and top-level functions in the same module. Unlike Java, there is no need to restrict a class to a module. 5. Words that begin with a capital letter for the class name (such as capwords, Pascal style), but the module name should be underlined in lowercase (such as lower_with_under.py). Although there are already many 13 existing modules that use a name similar to capwords.py, it is now discouraged because if the module name happens to coincide with the class name, it can be confusing. Python's parent Guido recommended specification type public Internalmodules lower_with_under _lower_with_underpackages lower_ With_underclasses capwords _capwordsexceptions capwordsfunctions lower_with_under ()  _ Lower_with_under () global/classconstantscaps_with_under _caps_with_underglobal/classvariableslower_with_ Under _lower_with_underinstance variables lower_with_under_lower_with_under  (Protected)  or__lower_with_under  (private) Method names lower_ With_under () _lower_with_under ()   (protected)  or__lower_with_under ()   (private) function/ Methodparameterslower_with_underlocal variables lower_with_undermain? Even a file that is intended to be used as a script should be imported. And a simple import should not cause the main function of this script (main functionality) to be executed, which is a side effect. The main function should be placed in a main () function. In Python, Pychecker, Pydoc, and unit tests require modules to be imported. Your code should always check if __name__ = = ' __main__ ' before executing the main program, so the main program will not be executed when the module is imported. Def main ():...if __name__ ==  ' _ _main__ ': Main ()    all top-level code will be executed when the module is imported. Be careful not to call functions, create objects, or perform actions that should not be performed when using Pychecker or Pydoc .  

Python Style Specification

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.