Python Coding Style Guide (reproduced)

zhaozj2021-02-16  86

Python Coding Style Guide ## Language: ZH '' Python Development Code Specification

--- HOXIDE LED DREAMINGK school pair release 040724 '' [[TableOfContents]] = Python Development Code Specification =

'' 'Code Style in the Coding Style of Python

== Introduction ==

THIS Document Gives Coding The Standard Library for The Main Python Describing Style Guidelines for the c code in the cimplementation of python [1].

The encoding convention given in this document applies to Python code that constitutes a standard library in the main Python release versions. Please refer to the relevant description of the C code style guide in Python's C implementation.

This document was adapted from Guido's original Python Style Guide essay [2], with some additions from Barry's style guide [5]. Where there's conflict, Guido's style rules for the purposes of this PEP. This PEP may still be incomplete (in fact, IT May Never Be finished ).

This document adapted from the first "Python Style Guide" in GUIDO. Add some of the content from "Barry's Style Guide" [5]. In the conflict, the Guide's style rules should be in line with this PEP (translation note) : When there is a conflict, it should be based on the Guido style) This PEP may still have not completed (actually, it may never end).

== 蠢 得用 consistency is the ignorant monster (a foolish constency is the hobgoblin of little minds) == (I really don't know how to turn it)

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project. ConsistenTency Within one module or function is Most Important.

The consistency in this style is important. It is more important in consistency within a project. The consistency within a module or function is most important.

But most importantly:... Know when to be inconsistent - sometimes the style guide just does not apply When in doubt, use your best judgement Look at other examples and decide what looks best And do not hesitate to ask!

But the most important thing is to know when it is inconsistent - sometimes not implemented style guidance. When you have doubts, use your best judgment. Take a look at other examples, then determine how it looks better. And ask!

Two Good Reasons To Break A Particular Rule: Break two good reasons for a set of established rules: (1) When Applying The rule Would Home The Code Less Readable, Even for Someone Who is buy to reading code triassows the rules.

(1) When this rule will lead to decline in code readability, even for someone, he is accustomed to reading the code according to this rule.

(2) To Be Consistent with Surrounding Code That Also Breaks - Althought to Clean Up Someone else's Mess (in true xp style).

(2) Break the rules in order to keep the rules (maybe historical reasons) - Although this is also a good opportunity to clear other confusion (true XP style).

== Code lay-out ==

=== Indentation ===

Use the default of Emacs' Python-mode:.. 4 spaces for one indentation level For really old code that you do not want to mess up, you can continue to use 8-space tabs Emacs Python-mode auto-detects the prevailing Indentation Level Used In a File and Sets ITS Indentation Parameters Accordingly.

The default value of the Python-Mode using Emacs: 4 spaces, an indentation level. For independent code, you don't want to make confusion, you can continue to use the 8 space tab (8-space tabs). Emacs Python-Mode Automatically discoverse the main indentation level in the file, set the indentation parameters.

=== Tabs or spaces (tabs or spaces)? ===

Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. The second-most popular way is with tabs only. Code indented with a mixture of tabs and spaces should be converted to using spaces exclusively. (In Emacs, select the whole buffer and hit ESC-x untabify.) When invoking the python command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly Recommended!

Never mix tabs and spaces. The most popular Python indentation method is to use only spaces, followed by using tabs. The code that mixes tabors and spaces will be converted into only spaces. In Emacs, select the entire buffer, press the ESC-X to remove the system.) When calling the Python command line interpreter, use the -t option to issue a warning for the unlailized mix tabs and spaces in the code (WARNINGS " ). WARNINGS will become an error (WARNINGS). These options are highly recommended .for New Projects, Spaces-Only Are Strongly Recommended Over Tabs. Most Editors Have Features That make this Easy to do. (In emacs, make sure indent-tabs-mode is nil).

For new projects, it is highly recommended to use only spaces-only instead of tabs. Many editors have functions that make it easy. (In Emacs, INDENT-TABS-MODE is NIL).

=== Maximum line length ===

There are still many devices around that are limited to 80 character lines; plus, limiting windows to 80 characters makes it possible to have several windows side-by-side The default wrapping on such devices looks ugly Therefore, please limit all lines to.. A Maximum of 79 Characters (Emacs Wraps Lines ". for flowing long blocks of text (DOCSTRINGS or Comments), Limiting The Length To 72 Characters Is Recommended.

There are still many devices that have been limited to 80 characters per line; and the window is limited to 80 characters to make a plurality of windows in parallel. Use the default folding (Wrapping) mode to look a bit ugly. Therefore, Please limit all rows to the maximum 79 characters (Emacs accurately limit the row to a length of 80 characters), and the large block text (document string or comment) is discharged sequentially, it is recommended to limit the length to 72 characters.

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued Line appriately. Emacs Python-Mode Does this right. Some Examples:

The preferred method of folding long line is to continue using Pyhon's parentheses, square brackets (Brackets) and Bracs (Braces). If necessary, you can add additional parentheses around the expression, but sometimes use The backslash looks better. Confirm that the continuation of the continuation. Emacs's Python-Mode is correctly completed. Some examples: {{#! Python Class Rectangle (blob): Def __init __ (Self, Width , EMPHASIS = None, highlight = 0): if width == 0 and Height == 0 and / color == 'red' and emphas == 'strong' OR / Highlight> 100: raise ValueError, "Sorry, You Lose" if width == 0 and Height == 0 and (color == 'red' or EMPHASIS IS NONE): Raise ValueError, "I don't think so" blob .__ init __ (self, width , HEIGHT, color, EMPHAS, HIGHLIGHT}}} === Blank Lines ===

Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch Of Related One-Liners (EG A Set of Dummy Implementations).

Use two lines to segment the top-level function and the definition of the class, the definition of the class method is divided with a single blank line. Additional blank line can be used in a group of (sparingly) segmentation related functions (Groups of related functions) ). The blank line can be omitted in a set of related single sentences. (For example, a set of dummy us)).

When Blank Lines Are Used to Separate Method Definitions, There IS Also A Blank Line Between The 'Class' Line and The First Method Definition.

There is a blank line between the 'Class' row and the first method definition when the space line is defined by the Method.

Use Blank Lines in functions, sparingly, to indeicate logical sections.

When using a blank line in a function, please use it to represent a logical segment (IE ^ L) Form Feed Character As whitespace; Emacs (and some printing tools) Treat these Characters AS Page Separators, SO You May Use The The Separate Pages of Related Sections of Your File.

Python accepts Contol-l (ie ^ l) switching panel as space; Emacs (and some print tools) depending on this character, so in your file, you can use them to be paid as a segment (Sections).

=== Encodings (PEP 263) ===

Code in the core Python distribution should aways use the ASCII or Latin-1 encoding (aka ISO-8859-1). Files using ASCII should not have a coding cookie. Latin-1 should only be used when a comment or docstring needs to mention an author name that requires Latin-1; otherwise, using / x escapes is the preferred way to include non-ASCII data in string literals An exception is made for those files that are part of the test suite for the code implementing PEP 263..

The code in the Python core publishing must always use ASCII or Latin-1 encoding (also name ISO-8859-1). The file using ASCII does not have to decode cookie (Coding cookie). Latin-1 is only when the annotation or document string involves Author name requires Latin-1, is used when it is used; additional / x escape character is a preferred method of containing non-ASCII (Non-ASCII) data in strings. Some files for test suices that implement code as PEP 263 are exceptions.

== Imports ==

- Imports Should Usually Be on Separate Lines, E.g .: - Imports should usually be imported in separate rows, for example:

{{{NO: IMPORT SYS, OS YES: IMPORT SYS IMPORT OS}}} It's} {{{{from type} {{{from type}}} - imports are always put at the Top of the file, just after any module commerss and docstrings, and before module global and constants. Imports Should Being, with the order being

- Imports is typically placed at the top of the file, after the module comment and document string, before the global variable and constant of the module. IMPORTS should be in order to set up.

1. Standard Library Imports 2. Related Major Package Imports (IE All Email Package Imports NEXT) 3. Application Specific Imports1. IMPORTS 2. Imports (MAJOR PACKAGE) import (ie, all EMAIL Package in subsequent imports) 3. Import of specific applications (Imports)

You Should Put a Blank Line Between Each Group of Imports. You should place an empty line between each group.

- Relative Imports for intra-package imports is the Absolute Package Path for All Imports.

- Imports of internal packages are not recommended to use relative import. The absolute path of the package is used for all imports.

- When Importing a class from a class-containing module, it's usually okay to spell this

- When importing a class from a module containing classes, you can usually be written: {{{from myclass import myclass from foo.bar.yourclass import youclass}}}}}}}}}}}}}}}}}}}}}}}}}}}} local name clalshes The local name conflict, then write {{{{{{{{{{"myclass.myclass"}} }.Bar.Yourclass.Yourclass}} {{{{"}} {{{{"}}. }} {{{"Myclass.myclass"}}}}}}}} }.yourclass "}}}.

== Space in expressions and statements (Whitespace in Expressions and Statements) ==

PET Peeves

Guido Hates Whitespace in The Following Places: Guido doesn't like space in the following places:

- Immediately Inside Parenthese, Brackets or Braces, AS in: {{{"SPAM (HAM [1], {Eggs: 2}". Always Write this as}}} {{"spam (HAM [1], { Eggs: 2}) ".}}} - next to parentheses, square brackets and curly brackets, such as: {{{" spam (HAM [1], {Eggs: 2} ".}}} should always Write it into {{{"spam (HAM [1], {Eggs: 2})".}}}

- Immedierately Before A Comma, Semicolon, or Colon, AS in: {{"IF x == 4: Print X, Y; X, Y = Y, X".}}}}}}}} {{" X == 4: Print x, y; x, y = y, x ".}}} - close to the comma, semicolon, or colon, such as: {{{" if x == 4: Print X, Y; x, y = y, x ".}}} To write it to {{{" IF x == 4: Print X, Y; X, Y = Y, X ".}}} - immediately before the Open Parenthesis That Starts The Argument List of a Function Call, AS IN {{{"Spam (1)".}}}}}}}} - Spam (1) ".}}} - Close to function call The parameter list pre-open parentheses, such as {{{"spam (1)}}}. To always write it into {{{" spam (1)}}}.

- Immedierately Before The Open Parenthesis That Starts An indexing or {{{{{{{{{{{{{{{{{{{{{{= {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{"DICT ['Key'] = List [index] ".}}} - in front of the open parentheses starting in the index or slice, such as: {{{" DICT ['Key'] = List [index] " To write it to "DICT ['Key'] = List [index]".}}}

- More Than One Space Around an Assignment (or Other) Operator To Align IT WITH ANOTHER, AS IN: - A single space around the assignment (or other) operator, such as: {{{# # ! python x = 1 y = 2 long_variable = 3}}} Always Write this as always writes it to {{{#! python x = 1 y = 2 long_variable = 3}}} (Don't Bother TO Argue with Him) On any of the Above - Guido's Grown Accustomed to this style over 20 years.) (Do not develop such a style for more than 20 years, do not fight any of the above and argue --- guido.)

=== Other Recommendations === {{{- Always Surround There Binary Operators with a single space on Either Side: assignment (=), Comparisons (==, <,>,! =, <>, <> =,> =, IS, NOT IN, IS, IS NOT >,! =, <>, <=,> =, In, not in, IS, is not), Boolean operation (AND, OR, NOT).

- Use Your Better Judgment for the insertion of spaces around archmetic operator. ALWAYS BE Consistent About Whitespace ON Either Side of a Binary Operator. Some Examples:}}} - Insert a space around the arithmetic operator around the arithmetic operator. Always stay binary The operator is consistent. Some examples: {{{#! Python i = i 1 submitted = submitted 1 x = x * 2 - 1 Hypot2 = x * x y * y c = (a b) * (ab) c = (a b) * (a - b)}}} - don't use space around the '=' Sign WHEN Used to indeicate a keyword argument or a default parameter value. for instance: - Don't Use spaces around the '=' number of keyword parameters or default parameter values, such as {{{#! Python Def Complex (REAL, IMAG = 0.0): Return Magic (r = real, i = imag)}}} - Compound Statements (Multiple Statements on the Same Line) Are Generally Discouraged. - Do not write multiple statements on the same row. {{{NO: if foo == 'Blah': do_blah_hes () YES: if foo == 'Blah': do_blah_thing ()

NO: do_one (); do_two (); do_three () YES: do_one () do_two () do_three ()}}}

== Comments ==

Comments That Contradict The Code Are Than No Comments. Always Make a priority of key the code changes! The inconsistency with the code is worse than the code. When the code is modified, you always prioritize your comments! Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).

The comment should be a complete sentence. If the comment is a phrase or sentence, the first letter should be capitalized unless he is an identifier starting with a lowercase letter (never modify the case case case).

IF a comment is short, the period at the end is best omitted. Block Comments generally consist of one or more paragraphs Built Out of Complete Sentences, And Each Sentence Should End In a Period.

If the comment is short, it is best to omit the end of the end (PERIOD? The end of the end of the end of the end, can it be a comma,) Comment block is usually composed of one or more paragraphs composed of the full sentence, each sentence should end with the end of the date .

YOULD USE TWO SPACES AFTER A SENTENCE-Ending Period, Since It Makes Emacs Wrapping and Filling Work Consistenty.

You should use two spaces after the end of the sentence, so that Emacs's broken lines and fill work coordinated (translation press: It should be made to work normally, "." Gives a prompt of the document structure).

Wennk and white apply. When writing English, the test and space are available.

Python Coders from Non-English Speaking Countries: please writ your comments in english, unless Will Never Be Read by People Who Don't speak your language.

Python programmers in English: Please write your comments in English, unless you do 120% of your credibility these code will not be read by people who don't understand your language.

=== Comment block (Block Comments) ===

Block comments generally apply to some (or all) code that follows them, and are indented to the same level as that code. Each line of a block comment starts with a # and a single space (unless it is indented text inside the comment) . Paragraphs inside a block comment are separated by a line containing a single #. Block comments are best surrounded by a blank line above and below them (or two lines above and a single line below for a block comment at the start of aa new section Of function definitions. Comment block is usually applied to follow some (or all) code and have the same indented level as those of these code. The comment block begins with '#' and a space in the note block (unless he is the contraction in the comment Into the text). The paragraph in the comment block is divided in line with only a single '#'. The comment block is preferably a hollow bundle (or one line in the upper two lines above, the comment for a new function definition).

=== Inline Comments === (Inline? Inline? Turn into "within the line")

An inline comment is a comment on the same line as a statement. Inline comments should be used sparingly. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space.

An annotation in a row is a comment in the same line. Inline comments should be cautious. Inline comments should be separated by at least two spaces and statements. They should start with '#' and individual spaces.

Inline Comments Are Unnecessary and in Fact Distracting if the state the obvious. Don't do this: {{{{x {{{{{{{}} If language is very clear, then in-line notes are unnecessary, fact It should be removed. Don't write this: {{{x = x 1 # increment x}}} but soliMetimes, this is useful: {{x = x 1 # Compensate for border}}} but sometimes This is good: {{{x = x 1 # Compensate for border}}}

== Document Strings (Documentation Strings) ==

Conventions for Writing Good Documentation Strings (A.K.A. "DOCSTRINGS") Are Immortalized in Pep 257 [3].

It should always be observed to write a good document string (also named "DOCSTRINGS") of the agreement (? Don't know how to translate) PEP 257 [3] .- Write Docstrings for all public modules, functions, classes, and methods. Docstrings Are Not Necessary for Non-Public Methods, But You Should Have A Comment That Describes What The Method Does. This Comment Should Appear After The "DEF" LINE.

- Write a document string for all public modules, functions, classes, and methods. Document strings are not necessary for non-public methods, but you should have a note that describes what to do. This comment should be in "DEF". Rear.

- PEP 257 Describes Good Docstring Conventions. Note That Most Importantly, The "" "That Ends a multiline docstring shouth be on a line by itself, E.g .:

- PEP 257 describes the agreement of a good document string. Be sure that "" "" "" "" "" "" "should be made alone, for example: {{{" "Return A Foobang

Optional Plotz Says To Frobnicate The BizBaz First. ""}}} - for one Liner Docstrings, it's okay to keep the closing "" "" "" "" "" "" in the same "" "on the single line of document string OK can also.

== Version bookkeeping == (I think "notes" better)

If you have to have rcs or cvs crud in your source file, do it as flollows.

If you want to put RCS or CVS miscellaneous (CRUD) in your source file, you can do it as follows. {{{#! Python __version__ = "$ Revision: 1.4 $" # $ source: E: / cvsroot / python_doc / PEP8.TXT, V $}}}} these Lines SHOULD BE INCLUDED AFORE Any Other Code, SEPARATED by a Blank Line Above and Below.

This line should be included in the module's document string, before all of the code, you can use a blank segmentation.

== Naming Conventions ==

The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent -. Nevertheless, here are the currently recommended naming standards New modules and packages (including 3rd party frameworks) should be written to these standards The name agreement of But WHERE An EXISTING LIBRARY HAS A DIFFERENT Style, INTERNAL CONSISTENCY IS Preferred.Python library is a bit confusing, so we will never make it completely - but still have a recognized naming norm. New module And the package (including a third party frame) must meet these standards, but for existing stocks in different styles, maintaining internal consistency is preferred.

=== Description: Descriptive: Naming Styles) ===

There Are A Lot of Different Naming Styles. IT Helps To Be Able To Recognize What Naming Style Is Being Used, Independently from What They Are Used for.

There are many different naming styles. The following helps identify the naming style being used, independent of their role.

The Following Naming Styles Are Commonly Distinguished:

The following naming style is well known:

- B (Single LowerCase Letter) - B (single lowercase letter)

- B (Single Uppercase Letter) - B (single uppercase letter)

- Lowercase

- Lower_case_with_underscores

- Uppercase

Upper_case_with_underscores

- Capitalized Words (or CapWords, or Camelcase - So named Because of the Bumpy Look of Its Letters [4]). This is Also Sometimes Known As StudlyCaps.

- CapitalizedWords (or CapWords, Camelcase - This name is because words can be distinguished from the case of the letter (morin?) Can be distinguished). This is sometimes treated as StudlyCaps.

- Mixedcase (Differs from Capitalizedwords By Initial LowerCase Character!) - Mixedcase (Different with CapitalizedWords lies in the first letters lowercase!)

- Capitalized_words_with_underscores (ugly!) - Capitalized_words_with_underscores (ugly!)

There's also the style of using a short unique prefix to group related names together. This is not used much in Python, but it is mentioned for completeness. For example, the os.stat () function returns a tuple whose items traditionally have names like st_mode, st_size, st_mtime and so on. The X11 library uses a leading X for all its public functions. (In Python, this style is generally deemed unnecessary because attribute and method names are prefixed with an object, and function names are prefixed with a Module Name.) Also uses a short special prefix to aggregate the related name. This is not used in Python, but for the integrity. For example, the Os.Stat () function returns a tuple, he The element is traditionally said, such as ST_MODE, ST_SIZE, ST_MTIME, etc. The X11 library is started with X. (in Python, this style is usually considered unnecessary, because the attributes and method names are prefixed by objects, and The function name is prefixed in module.)

In Addition, The Following Special Forms Using Leading or Trailing underscores Are Recognized (Thase Case Convention):

In addition, special forms of preamble or ending below are recognized (these usually combined with any habits (use?):

- _single_leading_underscore: weak "internal use" indicator (eg "from M import *" does not import objects whose name starts with an underscore) - _single_leading_underscore (single underscore as the leader): weak "internal use (internal use)" sign. (For example, "from m import *" does not import the following scribeted objects).

- single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, eg "Tkinter.Toplevel (master, class _ = 'ClassName')" - single_trailing_underscore_ (single end underlined): to avoid conflicts with Python keyword, for example. " Tkinter.toplevel (Master, Class_ = 'ClassName').

- __double_leading_underscore: Class-Private Names asyl python 1.4. - __double_leading_underscore: From Python 1.4, it is private.

. - __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces, eg __init__, __import__ or __file__ Sometimes these are defined by the user to trigger certain magic behavior (eg operator overloading); sometimes these are inserted by the infrastructure for its own use or for debugging purposes. Since the infrastructure (loosely defined as the Python interpreter and the standard library) may decide to grow its list of magic attributes in future versions, user code should generally refrain from using this convention for its own use. user code that aspires to become part of the infrastructure could combine this with a short prefix inside the underscores, eg __bobo_magic_attr__ - __double_leading_and_trailing_underscore__:. "magic" objects or attributes present in the user control (user-controlled) namespace, for example: __ init__ , __import__ or __file__. Sometimes they are defined by the user to trigger a magic behavior (for example: operator overload); Sometimes the constructor is inserted in order to use or for debugging. Therefore, in the future version, the constructor (loosely defined as the Python interpreter and standard library) may intend to establish a list of its own magic attributes, user code usually This convention should be limited to use. The user code to be part of the constructor can use a short prefix in a decline in a down slide, for example. __BoBO_MAGIC_ATTR __. === Description: Naming convention (PREScriptive: Naming Conventions) ==== === Names to Avoid ====

Never use the characters `l '(lowercase letter el),` O' (uppercase letter oh), or `I '(uppercase letter eye) as single character variable names. In some fonts, these characters are indistinguisable from the numerals one and ZERO. WHEN TEMPTED TO USE `L 'USE` L' INSTEAD.

Never use characters `L '(lowercase letters EL (ie, the same)),` o' (uppercase letter OH), or `i '(uppercase letter Eye) as a single-character variable name. In some fonts These characters cannot be distinguished from numbers 1 and 0. Try to replace it with `L 'when using` L'. ==== Module name ====

Modules Should Have Short, LowerCase Names, Without Underscores.

The module should be no underlined, short, lower-write name.

Since module names are mapped to file names, and some file systems are case insensitive and truncate long names, it is important that module names be chosen to be fairly short - this will not be a problem on Unix, but it may be a Problem When the code is transported to mac or windows.

Because the module name is mapped to the file name, some file system is not sensitive and truncated long name, the module name is selected as a pretty short --- This is not a problem in UNIX, but when the code is transmitted to Mac or Windows It may be a problem.

WHEN An Extension Module Written In C or C Has An Accompanying Python Module That Provides A Higher Level (E.G. More Object Oriented) Interface, The C / C Module Has a Leading Underscore (E.G._Socket).

When the extended module written in C or C has a C / C module with a lower line leader (such as _Socket) with the Python module (such as a more object oriented) interface (such as a further object guide).

Python Packages Should Have Short, All-Lowercase Names, WITHOUT Underscores.

Python packets should be named without underscore, short, and lower.

==== Class names ====

Almost Without Exception, Class Names Use The CapWords Convention. Classes for Internal Use Have a Leading Underscore In Addition.

Almost unsuitable, class names use the CapWords convention. Outside the category used in the internal use of the preamble.

==== Exception names ====

IF A Module Defines A SINGLE Exception Raised for All Sorts of conditions, IT IS generally caled "error" or "error". IT Seems That Built-in (Extension) Modules Use "Error", While Python Modules Generally Use "Error". The Trend Seems to Be Toward CapWords Exception Names. If the module defines a single exception on all situations, it is usually called "error" or "error". It seems to be built (extension) The module uses "Error", and the Python module usually uses "error" (for example: xdrlib.error). The trend seems to be tendency to use the CapWords exception name.

==== Global Variable Names ====

(Let's hope that these variables are meant for use inside one module only.) The conventions are about the same as those for functions. Modules that are use via designed for "from M import *" should prefix their globals (and internal functions and classes WITH An Underscore to Prevent Exporting Them. (Let us pray that these variables are only in the internal meaning of one module), the same as in the function. The module is designed to be used by "from m import *", must Use a prefix of global variables (and internal functions and classes) from being exporting.

==== Function names ====

Function names should be lowercase, possibly with words separated by underscores to improve readability. MixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.

The function name should be lowercase, which may use a loop style word to increase readability. MixedCase is only allowed to be used in this style of context (such as: threading.py) to remain backwards.

==== Method name and instance variable (Method Names and Instance Variables) ====

The Story Is Largely The Same As with funercs: in General, Use Lowercase with Words Seprated by underrescracsery. This is the same. This is the same. This is the same: Utty lower-write words, if necessary, use underscore to separately increase readability.

Use one leading underscore only for internal methods and instance variables which are not intended to be part of the class's public interface Python does not enforce this;. It is up to programmers to respect the convention.

A preamble is used only for internal methods and instances that are not intended as a common interface. Python does not enhance this; it depends on whether the programmer complies with this agreement.

Use two leading underscores to denote class-private names Python "mangles" these names with the class name:.. If class Foo has an attribute named __a, it can not be accessed by Foo .__ a (An insistent user could still gain access by calling FOO._FOO__A.) Generally, Double Leading Undes Should Be Used Only To Avoid Name Conflicts with Attributes in Classes Designed to Be Subclassed.

Use two leading scribes to indicate the private name. Python connects these names and class names: If the class foo has a property name __a, it cannot be accessed with foo .__ a. (Visible users (an insistent user ) Or accessibility can be obtained by foo._foo__a.) Typically double-front guide only is only used to avoid the name of the name of the attribute name in the class class. (Not too smooth)

==== Designing for inheritance ====

Always decide whether a class's methods and instance variables should be public or non-public. In general, never make data variables public unless you're implementing essentially a record. It's almost always preferrable to give a functional interface to your class instead (and some Python 2.2 Developments Will make this much nuch nic.

Always determine if the methods and instance variables in a class are to be disclosed. Usually, do not disclose the data variables, unless you implement it in essentially record. People almost always preferred to give a function as a class interface (Some developers of Python 2.2 are doing very beautiful at this point).

Also decide whether your attributes should be private or not. The difference between private and non-public is that the former will never be useful for a derived class, while the latter might be. Yes, you should design your classes with inheritence in mind! Similarly, determine if your properties should be private. Private and non-private differences are that templates will never be valid for the original class (export class), and the latter can. Yes, you should use inheritance in your brain. Designed your class.

Private Attributes Should Have Two Leading Underscores, no trailing understandcores.

Private attributes must have two leading scribes, and there is no underline.

Non-Public Attributes Should Have A Single Leading Underscore, No Trailing Underscores.

Non-public properties must have a leading underline, and there is no underline.

Public attributes should have no leading or trailing underscores, unless they conflict with reserved words, in which case, a single trailing underscore is preferrable to a leading one, or a corrupted spelling, eg class_ rather than klass. (This last point is a bit ................ ..

Public attributes have no preambles and backward underscores unless they are conflict with reserved words, in this case, single backcrosses are better than spelling than pre-placed or confused, for example: Class_ is better than Klass. The last point is some dispute; if compared Class_ You prefer KLASS, then this is just a consistency problem.

== ProGramming Recommendations ==

- Comparisons to Singletons Like None Should Always Be Done with 'Is' or 'Is Not'. Also, BEWARE OF WRITING "ife" WHEN You Really Mean "IF] - EG WHEN TESTING WHETHER A VARIABLE OR ARGUMENT That Defaults to None Was Set To Some Other Value. The Other Value Might Be a value That False In A Boolean Context!

- Comparison of single elements, such as None should always be used: 'is' or 'is not'. When you are "if x is not none", you should be careful about "IF X" - for example When you test a variable or parameter of None or whether the parameter is set to other values. This value may be False in the Boolean Context.

- Class-based exceptions are always preferred over string-based exceptions Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in Exception class Always include a class docstring E.g .:...

- Based on the exception of the class is always better than the string-based exception. Modules and packets should define their own domain-specific basis, base classes should be subclasses of built-in Exception class. Also included A class of document strings. For example: {{{#! Python class messageerror (Exception): "" "Base Class for errors in the email package." "}}} - use string methods instead of the string module UnlessStead of the String Module UnlessN -compatibility with Versions Earlier Than Python 2.0 Is Important. String Methods Are ALWAYS MUCH FASTER AND Share The Same API with Unicode Strings.

- Use a string method instead of a string module unless you must compatible with Python 2.0. The string method is always very fast, and the same API is shared with the Unicode string (application interface)

- Avoid Slicing Strings When Checking for prefixes or suffixes. Use StartSwith () And endswith () INSTEAD, SINCE They defix: - Avoid slicing the string when checking prefixes or suffixes. STARTSWITH ( ) And endswith () instead because they are clear and wrong. For example: {{{NO: IF foo [: 3] == 'bar': yes: if foo.startswith ('bar'):}} } The Exception is if your code Must Work with Python 1.5.2 (But Let's Hope Not!).

Exception is if your code must work in Python 1.5.2 (but we hope that it will not happen!).

- Object Type Comparisons Should Always Use isinstance () Instead of Comparing Types Directly. EG - The comparison of object types should always be used instead of direct comparison types. For example: {{{NO: if Type (OBJ) IS TYPE (1) YES: ISINSTANCE (OBJ, INT):}}} When Checking if An Object IS A String, Keep In Mind That It Might Be a Unicode String Too! In Python 2.3, Str And Unicode Have A Common Base Class, BaseString, SO you can do: Check if an object is a string, tight it may be a Unicode string! There is a public base class in Python 2.3, Str and Unicode, BaseString, so you can do this: {{if isinstance (Obj, BaseString):}}} in Python 2.2, The Types Module Has The StringTypes Type Defined for That Purpose, EG:

In the Python 2.2 type module, the StringTypes type is defined for this, for example: {{{#! Python from Types Import stringtypes if isinstance (obj, stringtypes):}}} in Python 2.0 and 2.0 and 2.1 in Python 2.0 and 2.1 You should do this: {{{#! Python from Types Import StringType, UnicodeType if Isinstance (Obj, StringType) OR / ISINSTANCE (OBJ, UnicodeType):}}} - for sequences, (strings, lists, tuples), USE The Fact That Empty Sequences Are False, SO "If NOT SEQ" or "IF SEQ" IS preformed to "if," or "if not len ​​(seq)". - sequence, string (string), List (list), tuples), using empty lists, is FALSE, so "if not seq" or "if SEQ" is better than "if Len (SEQ)" or "if not len ​​(seq)".

- Do not write string literals that rely on significant trailing whitespace Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) will trim them -.. When you write a string literal Do not rely on meaningful post Space. This back space is visually unrecognizable, and some editor (especially recent, reindent.py) will repair them.

- Don't compare boolean value == (Bool Types area new in python 2.3): - Do not use == to compare the Boolean value to determine TRUE or FALSE (Boolean is pythn 2.3 new {{{NO: if Greeting == True: YES: if Greeting: No: if Greeting == True: YES: if Greeting:}} -------------------------------------------- ----

转载请注明原文地址:https://www.9cbs.com/read-12305.html

New Post(0)