91 Tips for improving Python programs reading notes 1

Source: Internet
Author: User

    1. Introduction


Recommendation 1: Understanding the concept of pythonic


pythonic may be able to shade the definition: The code style that fully embodies Python 's own characteristics.


Two variable exchanges in python need only one line :


a,b= B,a

To traverse a container, you can:

For i in Alist:    do_sth_with (i)

To open a file, you need a secure close file to:

With open (path, ' R ') as F:     Do_sth_with (f)

If you want to output a list in reverse, you can do this:

Printlist (Reversed (a))

Writing pythonic programs requires a good understanding of the standard library, especially built-in functions and built-in data types. For example, for string formatting, it is generally written like this:print ' hello%s! '% (' Tom '). In fact, the %s is very readable, because after a lot of, it is difficult to distinguish between the placeholder for which argument, so the pythonic code is like this.

print ' Hello% (name) s! '% (' Name ': ' Tom ') value= {' great ': ' Hello world ', ' language ': ' Python '}print ' percent (greet) s from% (language) s. '%valueprint ' { Greet} from {language} '. Format (greet = ' helloworld! ', language = ' python ')

Recommendation 2: Writing pythonic code

(1). To avoid deterioration of the code

1 Avoid using case only to distinguish different objects

2 Avoid the use of confusing names

3 Don't be afraid of too long variable names

(2). In-depth knowledge of Python helps to write pythonic code

1 Full mastery of all the features that Python provides to us, including language features and library features. One of the best ways to learn is to read through the Official Handbook of languagereference and libraryreference.

2 with the update of the Python version, knowledge will be updated as well.

3 In-depth study of the industry recognized comparison pythonic code, such as Flask,gevent,requests and so on.


Recommendation 3: Understand the differences between python and C language

(1). ' Indent ' with '{} '

python uses strict code indentation to separate blocks of code, so spaces and tab keys cannot be tapped.

(2). ' and

There is a strict difference between ' and ' in the C language, in Python , single and double quotes, and there is a slight difference in the input string content only.

(3). Ternary operator '? :’

c?x:y equivalent in python in the form of xif c else y

(4). switch...case

There are no such branching statements in Python , but you can use the ifelif. else instead.

Or use a jump table to implement

def f (x):     return{     0: "youtyped zero.\n",     1: "Youare in top.\n",     2: "Nis an even number\n"}.get (N, " Only single-digit numbers areallowed\n ")


Don't be confused with other language thoughts and habits, mastering Python 's philosophy and way of thinking is the hard truth.


Recommendation 4: Add comments appropriately in your code,

There are 3 types of code comments in python : block comments, line comments, and document comments. These three forms of idioms are roughly the following:

(1). Use block annotations to annotate only complex operations, algorithms, and potentially difficult-to-understand techniques or code that is not straightforward enough.

(2). Comments and code are separated by a certain distance, and it is best to leave a few lines of space after the block comment to write the code.

(3). Add document annotations to externally accessible functions and methods. Note to clearly describe the functionality of the method, and describe the parameters, return values, and possible exceptions, so that the person who calls it externally will be able to use the docstring only.

(4). It is recommended to include the Copyright Declaration, module description, etc. in the file header, and to consider adding the author's information and change records if necessary.


Recommendation 5: Exercise code layout more elegantly with appropriate add empty

In a team, maintaining a good code format requires team members to follow and apply based on selecting a set of appropriate code formatting rules. Often the code is constantly being modified, and all readability is directly related to maintainability and extensibility.

(1). After a set of code has expressed a complete idea, it should be spaced with blank lines.

(2). Try to keep the contextual semantics easy to understand, such as when a function calls another function, try to put them together, the best caller is on, the callee is down.

(3). Avoid too long lines of code, preferably not more than three characters per line. The parts that are over can be concatenated in parentheses and keep the elements vertically aligned.

(4). Do not use extra spaces in order to maintain horizontal alignment, making it easier for readers to understand the code more important.

(5). The use of spaces to be able to warn the reader when it is necessary to emphasize, the two-dollar operator should have spaces around the left and right, commas and semicolons before the use of spaces, between the function name and the opening parenthesis, the sequence index operation when the sequence name and [] do not need spaces between the function default parameters do not need spaces, Use spaces when emphasizing the previous operator.


Recommendation 6: Four principles for writing a function

Functions can bring maximum code reuse and minimize code redundancy. General function design has the following basic rules can be consulted:

Principle 1 function design should be as short as possible, nesting level should not be too deep. The so-called short, is mentioned earlier as far as possible to avoid too long function.

Principle 2 function declaration should be reasonable, simple, easy to use. In addition to the function name can reflect its general function, the number of parameters is also not too much.

Principle 3 The function parameter design should consider backwards compatibility. Sometimes with the need and version of the upgrade needs to make certain changes to meet this version of the requirements, design process in addition to the current needs to consider backward compatibility

Principle 4 A function only does one thing, try to keep the consistency of the function statement granularity.


Recommendation 7: Centralize constants into one file

In fact, Python 's built-in namespaces support a small number of constants, such as True,False,None , and so on, how do we use constants? There are generally two ways of doing this.

(1). By naming the style to remind the user that the meaning of the variable is a constant, the normal name of all the letters capitalized, underline each word, suchas max_overflow, total. It's a conventional style.

(2). Implements the constant functionality through a custom class. This requirement is in accordance with the terms named all uppercase and the value once binding is no longer modifiable. The following is a common workaround that satisfies the two criteria for the above constants by modifying the value corresponding to the constant or by throwing an exception when the name does not conform to the specification.

#const. Pyclass_const:     classconsterror (typeError):  pass     classconstcaseerror (consterror):  Passdef  __setattr__ (self,name,value):       if Self.__dict__.has_key (name):       raise self. Consterror, "Can ' t change const%s"%name       if isn't Name.isupper ():       raise self. Consrcaseerror, ' const name '%s ' is not all uppercase '%name       self.__dict__[name]= valueimport  syssys.modules[ __name__]= _const ()

Import Const directly when using

Import  constconst.company= "IBM"

Regardless of the way you implement constants, it is advocated to centralize constants into a single file, as this facilitates maintenance, and once you need to modify the values of the constants, you can centralize them instead of checking them individually.


91 Tips for improving Python programs reading notes 1

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.