Python Code style recommendations

Source: Internet
Author: User
Tags instance method string methods

Python is well-known for its structure, but also known for its naming conventions, chaotic and irregular naming especially for developers to bring understanding of the misunderstanding.

In particular, like Python, ruby Dynamic language, the naming of rules is especially important due to the possibility of adding or subtracting methods or attributes at any time during the run time. The Ruby language itself defines the grammatical rules more arbitrarily, but there are no lack of one by one corresponding to the implied rules, make people at a glance. Its naming rules even penetrate into the language itself in the specification of the naming rules that Python appears to have no distance. It is necessary to develop a good coding naming specification gradually. This article collects some code style, naming specification from each major site article.  Easy to learn reference. Code style:
  1. Use an empty glyd to represent indentation Instead of tab tab, and do not mix the two
  2. Wrap at least one line between functions
  3. Wrapping at least two lines between classes
  4. Dict, list, tuple, parameter list, you should add a space before the comma.
  5. Colon after key in dict: a space should be added between the value and the colon: instead of: Before the key
  6. A longer code (greater than 79chars) uses a backslash \ line break. The beginning of the new line should be aligned with the previous delimiter (the argument wrapping is the same as the left parenthesis (aligned
  7. Import is after module comments and docstring, before the constant declaration
  8. 3.0 The version of the code file is suggested to encode Latin characters. More than 3.0 recommended Utf-8
  9. There are operator operations in the code, note the precedence, the first action crunch, or parentheses
  10. Do not add spaces around the equals sign
  11. Try not to put multiple lines on the same line
  12. Use less inline comments (post-line comments)
  13. Block Comments (multi-line function comment starting with #), keeping the same indentation as the target function
  14. DocString, the first line writes the return value, the next line writes the function function description, after can follow the format >>>func (arg1, arg2, ARG3)/R return value. For easy testing
  15. Also, to use source control tools such as Subversion,cvs. After the docstring of the function, the code will be written before the
    1. __version__ = "Revision:dd63848921 "
Naming rules:
  1. Use as little as possible ' l ' (lowercase letter el), ' O ' (uppercase), or ' I ' (uppercase letters eye) as a variable named.-------No L,i,o
  2. The packages and modules should be in short and all lowercase letters (Modules should has a shorter, all-lowercase names.): Thismoduleisnew
  3. Class name is recommended in the form of capwords (first capitalization): Newclassname
  4. The exception class is named after the error-terminated string: NewError
  5. Global variables are designed to be used within a module, and the __all__ mechanism within the package can be used to remove global variables when using import *
  6. The function name is as small as possible, and the word is concatenated with _ (underscore), and the mixedcase vegetation of mixed size is allowed for use in traditional classes. Function_name (Arg1 ...)
  7. function and Method parameters (functions and methods arguments), self as the first parameter of the instance method, the CLS as the first parameter of the class method, if the parameter name is the same as the keyword, in order to avoid, you should add an underscore
  8. The property of the method name & class instance (method name & instance variable) is the same as the function name, and the private method of the class instance private property and class instance starts with a single underscore _private_fucntion_name (self )
  9. constant; All uppercase, between words with _ Arc interval: This_is_constant_var
  10. Object-Oriented design recommendations:
    1. If the property in the class instance is set to public or private, consider setting it to private, which is less expensive to modify.
    2. Private cannot be used by third parties because they may be deleted or discarded at any time.
    3. The public property cannot begin with an underscore
    4. Avoid attributes using large operand operations
    5. If you do not want the property inherited by the quilt class, you should start with a double underscore and not be underlined at the end. This will start Python's naming recognition corrective processing algorithm to ensure that it is not inherited
    1. Joined_lower can be a function name Method Name Property name
    2. All_caps is a constant
    3. StudlyCaps is the class name
    4. CamelCase only used in pre-ordered naming conventions
    5. Attribute interface,_internal, __private
    6. Try to avoid __private form, the following two connections explain why there is no private statement in Python
There is no time to translate at last, there is time to come again. reference:http://www.python.org/dev/peps/pep-0008/#naming-conventions Programming recommendations
  • Code should is written in a-the-does not disadvantage-other implementations of Python (PyPy, Jython, Ironpytho N, Cython, Psyco, and such).

    For example, does not rely on CPython ' s efficient implementation of in-place-string concatenation for statements in the F orm  A + = b  or  a = a + b . Those statements run more slowly in Jython. In performance sensitive parts of the library, the  ". Join ()  form should be used instead. This would ensure that concatenation occurs in linear time across various implementations.

  • Comparisons to singletons-like None should always be do with is or was not, never the equality operator S.

    Also, beware of writing if x when you really mean if x are not None--e.g. when testing whether a Variab Le or argument that defaults to None is set to some and other value. The other value might has a type (such as a container) that could is false in a Boolean context!

  • When implementing ordering operations with rich comparisons, it's best to implement all six operations (__eq__, __ne__, __lt__, __le__, __gt__, __ge__) rather than relying on other code to Only exercise a particular comparison.

    To minimize the effort involved, the functools.total_ordering () Decorator provides a tool to generate missing C Omparison methods.

    PEP 207 indicates that reflexivity rules  is  assumed by Python. Thus, the interpreter may swap  y > x  with  x < y ,   y >= x   with  x <= y , and may swap the arguments of  x = = y  and  x! = y . the  sort ()  and  min ()  operations is guaranteed to use the  <  operator and the  Max ()  function uses the  ;  operator. However, it is the best-implement all six operations-confusion doesn ' t arise in other contexts.

  • Use class-based exceptions.

    String Exceptions in new code was forbidden, because this language feature was being removed in Python 2.6.

    Modules or packages should define their own domain-specific base exception class, which should is subclassed from the B Uilt-in Exception class. Always include a class docstring. e.g.:

     class Messageerror (Exception): "" "Base class for errors in the e-mail package." "

    Class Naming conventions apply here, although you should add the suffix "Error" to your exception classes, if the EXCEP tion is an error. Non-error exceptions need no special suffix.

  • When raising a exception, use raise ValueError (' message ') instead of the older form raise ValueError, ' Messa GE '.

    The Paren-using form is preferred because when the exception arguments be long or include string formatting, you don ' t NE Ed to use line continuation characters thanks to the containing parentheses. The older form would be removed in Python 3.

  • When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

    For example, use:

    Try:    import platform_specific_moduleexcept importerror:    platform_specific_module = None

    A bare except: clause'll catch Systemexit and keyboardinterrupt exceptions, making it harder to interrupt a pro Gram with control-c, and can disguise other problems. If you want to catch all exceptions this signal program errors, use except Exception: (bare except is equivalent To except baseexception:).

    A good rule of thumb is the to limit use of the bare ' except ' clauses to both cases:

      1. If the exception handler would be is printing out or logging the traceback; At least the user would be aware, that's the error has occurred.
      2. If the code needs to does some cleanup work, and then lets the exception propagate upwards with raise. try...finally can be a better-handle this case.
  • Additionally, for any try/except clauses, limit the  try  clause to the absolute minimum amount of Code necessary. Again, this avoids masking bugs.

    Yes:

     try:value = collection[key]except keyerror:return key_not_found (key) Else:return Handle_value (value) 

    No:

     Try: # Too broad! Return Handle_value (Collection[key]) except Keyerror: # would also catch Keyerror raised by Handle_value () return Key_ Not_found (key) 
  • Context managers should be invoked through separate functions or methods whenever they doing something other than acquire and Release resources. For example:

    Yes:

    With Conn.begin_transaction ():    do_stuff_in_transaction (conn)

    No:

    With Conn:    do_stuff_in_transaction (conn)

    The latter example doesn ' t provide any information to indicate that the __enter__ and __exit__ methods is doing something Other than closing the connection after a transaction. Being Explicit is important in the this case.

  • Use string methods instead of the string module.

    String methods is always much faster and share the same API with Unicode strings. Override This rule if backward compatibility with Pythons older than 2.0 is required.

  • Use ". StartsWith () and ". EndsWith () instead of string slicing to check for prefixes or suffixes.

    StartsWith () and EndsWith () is cleaner and less error prone. For example:

    Yes:if foo.startswith (' Bar '): No:  if foo[:3] = = ' Bar ':

    The exception is if your code must work with Python 1.5.2 (but let ' s hope not!).

  • Object type comparisons should always use Isinstance () instead of comparing types directly.

    Yes:if isinstance (obj, int): No:  if Type (obj) is type (1):

    When checking if an object was a string, keep in mind that it might be a Unicode string too! In Python 2.3, str and Unicode has a common base class, basestring, so can do:

    If Isinstance (obj, basestring):
  • For sequences, (strings, lists, tuples), use the fact, empty sequences is false.

    Yes:if not seq:     if Seq:No:if len (seq)    if not len (seq)
  • Don ' t write string literals that rely on significant trailing whitespace. Such trailing whitespace is visually indistinguishable and some editors (or more recently, reindent.py) would trim them.

  • Don ' t compare Boolean values to True or False using = =.

    Yes:   If greeting:no:    if greeting = = True:Worse:if Greeting is True:
  • The Python standard library would not use function annotations as, would result in a premature commitment to a particul AR annotation style. Instead, the annotations is left for users to discover and experiment with useful annotation styles.

    Early Core Developer attempts to use function annotations revealed inconsistent, Ad-hoc annotation styles. For example:

    • [STR] was ambiguous as-whether it represented a list of strings or a value that could be either str o R None.
    • The notation open (file: (str,bytes)) is used for a value, could be either bytes or str rath Er than a 2-tuple containing a str value followed by abytes value.
    • The annotation seek (Whence:int) exhibited a mix of over-specification and under-specification: int is t OO restrictive (anything with __index__ would being allowed) and it is not restrictive enough (only the values 0, 1, and 2 are allowed). Likewise, the annotation write (b:bytes) was also too restrictive (anything supporting the buffer protocol would be allowed).
    • Annotations such as read1 (N:int=none) were self-contradictory since None is not a int. Annotations such as Source_path (self, FULLNAME:STR)-objectwere confusing about what the return type should Be.
    • In addition to the above, annotations were inconsistent in the use of concrete types versus abstract types: int v Ersus Integral and Set/frozenset versus Mutableset/set.
    • Some annotations in the abstract base classes were incorrect specifications. For example, Set-to-set operations require and other to being another instance of set rather than just an I Terable.
    • A further issue is that annotations become part of the specification but weren ' t being tested.
    • In most cases, the docstrings already included the type specifications and do so with greater clarity than the function a Nnotations. In the remaining cases, the docstrings were improved once the annotations were removed.
    • The observed function annotations were too ad-hoc and inconsistent to work with a coherent system of automatic type Checki ng or argument validation. Leaving these annotations in the code would has made it more difficult to make changes later so that automated utilities could be supported.

Python Code style suggestions (GO)

Related Article

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.