Python Common Programming Specification summary

Source: Internet
Author: User

Pythonic definition

Python's most commonly used coding style is PEP8, see: http://jython.cn/dev/peps/pep-0008/

Pythonic is really hard to define, just a few classic explanations from the Zen of Python:

Beauty is better than ugliness (Python's goal of writing graceful code) is better than obscure (beautiful code should be clear, naming specification, style similar) simplicity is better than complexity (graceful code should be concise, not complex internal implementations) complex than messy (if complex unavoidable, The code can not be difficult to understand the relationship, to keep the interface concise) flat is better than nesting (graceful code should be flat, not too many nesting) interval than compact (graceful code has the appropriate interval, do not expect a line of code to solve the problem) readability is important (beautiful code is readable)

For a simple example, the code for the Quick sort algorithm using the Pythonic style encoding is as follows:

def quicksort (array): less    = [];    Greater = [];    If Len (array) <= 1:        return array    pivot = Array.pop () for    x in array:        if x <= pivot:            less.append (x)        else:            greater.append (x)    return quicksort (less) + [pivot] + quicksort (greater)
Pythonic Code Style
    • Swap two variables

The C language code is as follows:

1 int a = 1, b = 2; 2 int tmp = A; 3 A = b; 4 B = tmp; 5  6//If all two variables are of integer type, they can also be used: 7  8 int a = 1, b = 2; 9 A = a^b;10 b = a^b;11 a = a^b;12 13//Such form, without introducing a third variable

The Pythonic code is as follows:

1 A, B = B, a
    • Python has the flexibility to use iterators to safely close file descriptors , as follows:
1 for i in Alist:2     do_sth_with (i) 3 4 with open (path, ' R ') as F:5     Do_sth_with (f)

Pythonic pursues the full play of the Python syntax, writing the code with a Python flavor, rather than looking at C or Java code;

    • Should not be used too skillfully
1 A = [1, 2, 3, 4]2 b = ' abcdef ' 3 print a[::-1]4 print b[::-1]

More people using Python can easily see its role, that is, the output of A and B in reverse order, but still more obscure, Pythonic pursuit is to make full use of the Python syntax, the above code can be written as:

1 A = [1, 2, 3, 4]2 b = ' abcdef ' 3 Print List (reversed (a)) 4 Print list (reversed (b))
    • String formatting

Many of us write this in general and are more concise:

1 name = ' Tom ' 2 age = ' 3 ' of print ' Hello%s, your age is%s! '% (name, age)

In fact, the%s is more readable, especially after the number, it is difficult to know which placeholder corresponds to which argument, compare Pythonic code as follows:

1 value = {' name ': ' Tom ', ' age ': '}2 print ' Hello% (name) s, your age is% (age) s! '% value

Using the% placeholder form, still not Python's most recommended, the most pythonic-style code is as follows:

1 print ' Hello {name}, your age was {age}! '. Format (name = ' Tom ', age = ' 20 ')

Str.format () is the most recommended method of string formatting for Python;

    • Packages and Modules

Packages and modules are named in lowercase, singular, and short;

Packages are typically only namespaces, and can contain only empty __init__.py files;

    • Too much if...elif...elif......else ... You should use a dictionary to implement
1 if n = = 0:2     print "You typed zero ..." 3 elif n = = 1:4 print "You is in     top ..." 5 elif N = = 2:6     print "n is even number ..." 7 else:8     print "Default value" 9 10 # Use a dictionary to achieve better some def f (x):     return {         0: "You typed zero ...",         1 : "You were in top ...",         2: "N is even number ...",     }.get (x, "Default value")
Write pythonic code to avoid deterioration of code
    • Avoid using case-by-case to distinguish different objects;
    • Avoid the use of confusing names, variable names should be consistent with the problem domain being solved;
    • Don't be afraid of long variable names;
Add appropriate comments to your code
    • Line annotations only annotate complex operations, algorithms, difficult-to-understand techniques, or code that is not readily apparent;
    • Note and code to separate a certain distance, whether it is a line of comments or block comments;
    • Add a document comment to externally accessible functions and methods (whether simple or not), note to clearly describe the functionality of the method, and describe the parameters, return values, and possible exceptions, so that the external callers can use the docstring only if they see them;
    • Recommended in the file header contains the Copyright Declaration, module description, etc.;
    • Comments should be used to explain the function of the code, the reason, and the idea that the code itself should not be interpreted;
    • The code that is no longer needed should be deleted instead of commented out;
Add empty Exercise code layout more elegant and reasonable
    • After a set of code expresses a complete idea, it should be spaced with blank lines, it is recommended to empty two lines between the function definition or the class definition, the empty line between the class definition and the first method, or where the semantic separation is required, and the empty row is inserted on the basis of the intrinsic connection between the code;
    • As far as possible to ensure the easy understanding of the upper and lower Wen, is usually the caller on the top, the callee under;
    • Avoid too long lines of code, preferably not more than 80 characters per line;
    • Do not use extra spaces in order to maintain horizontal alignment;
Several principles for writing functions
    • function design should be as short as possible, nesting level should not be too deep;
    • function declaration should be reasonable, simple, easy to use, function name should be able to correctly reflect function general function, parameter design should be concise and clear, the number of parameters should not be too much;
    • The design of function parameters should consider backward compatibility;
    • A function only does one thing, as far as possible to ensure the consistency of function statement granularity;
Centralize constants into one file

Python does not provide a direct way to define constants, and there are generally two ways to use constants;

    • By naming the style to remind the user that the meaning of the variable represents a constant, the normal volume of all letters capitalized, with an underscore to connect each word, such as max_number,totle, etc.;
    • By customizing the class to implement the constant function, the constants required to comply with two points, first, the name must be all uppercase, the second is the value once the binding can not be modified;
1 class _const:2  3     class Consterror (TypeError): Pass 4     class Constcaseerror (consterror): Pass 5  6     def __setattr__ (self, Name, value): 7         If name in self.__dict__: 8             -Rasie self. Consterror, "Can ' t change const.%s"% name 9         if not Name.isupper (): Ten             raise self. Constcaseerror, "const name '%s ' isn't all uppercase"% name11         self.__dict__[name] = value13 import Sys15 sys.m ODULES[__NAME__] = _const ()

In either case, the constants should be centralized into a single file for easy maintenance and management.

Python Common Programming Specification summary

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.