Anti-patterns in Python programming

Source: Internet
Author: User

Python is one of the most popular programming languages of all. Concise and expressive syntax, two or three lines of code can often solve the problem of ten lines of C code to solve, a wealth of standard libraries and third-party libraries, greatly saving development time, so that it is the performance of non-stringent requirements of the development task of choice; strong and active community, complete documentation, Also makes many programming beginners choose it as their first programming language. There are even reports abroad that Python has become the most popular programming language for beginners in America's top universities.

To learn a programming language is not easy, in the beginner stage, to correct some of the wrong practices, the future of deep learning is crucial. A blogger named Constantine Lignos, a postdoctoral researcher at the radiation Research Department at the Children's Hospital of Pennsylvania, recently wrote a very meaningful article outlining the most common mistakes that beginners of Python students make, classifying and dissecting these errors, and their contents sketchy , well worth learning for every Python beginner.

This article gives some examples of anti-patterns that are common to beginners in python, which often refer to usages that do not conform to the habit or that can lead to bad results. Lignos his summary of the anti-patterns into four categories-iteration, performance, variable vulnerability and programming style. Let's take a look at an example to understand where these anti-patterns are "anti".

Iteration

When we need to iterate a range of numbers simply, Python gives us a very useful function: range. Lignos observed that some beginners like to use range to iterate through the list of tables, as in the following form:

For I in range (len (alist)):    print Alist[i]

This code is not a problem now, but it is not in Python's habit. But the following code has a problem:

Alist = [' Her ', ' name ', ' was ', ' Rio ']for I in range (0, Len (alist)-1): # missing out last    print I, Alist[i]

We can take a look at an example of the official Python document range:

>>> Range (1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The right interval of range is not included, and if it is influenced by intuition or other programming language, then minus 1 is wrong. Lignos also lists several other iterations of the error pattern, and we just need to remember that range should be used in an iteration of a number range.

Performance

Lignos gives two pieces of code:

Lyrics_list = [' Her ', ' name ', ' was ', ' rio ']words = make_wordlist () for word in words:    if Word in lyrics_list: # linear time 
   
    print word, "is in the lyrics"
   

And

Lyrics_set = set (lyrics_list) words = make_wordlist () for word in words:    if Word in Lyrics_set: # constant Time        print word, " is in the lyrics "

Which mode is more efficient? Lignos comments have been given the answer. The comment means that determining whether an element exists in a set of elements, the algorithm complexity of using list is O (n), and the algorithm complexity of using Set is O (1). Is the set always better than list? In other cases, which data structure should be used? The official Python wiki has a document for the time complexity of each data structure operation, which is more important than the answer itself, for reference. As for why, only Python's source code can tell us.

The vulnerability of a variable

Beginners tend to assume some assumptions that should not be assumed and are poorly considered for some abnormal processes. Lignos also gives an example:

For IDX, value in Enumerate (y):    if value > Max_value:        breakprocesslist (y, idx)

Here y if it's empty, then there's a problem, because IDX is not defined at all, and eventually we get a Nameerror exception. A good practice is to give IDX a default error value, in C language we often like to use-1. The following code is considered to be more comprehensive:

def find_item (item, alist):    # None is better than 1 for python.    result = 1 for    idx, Other_item in Enumerate (alist):        if Other_item = = Item:            result = idx break    return result
Code style

Python has a code style guidance document PEP 8, and these rules are justified. When the scholar did not understand why, the best way is to abide by it as far as possible, until there is a deeper understanding will be enlightened, colleagues will understand when the rules can be broken. Lignos cites some examples of this document, such as how to test if a variable is empty, if testing a variable is none, and so on.

The above analysis of some of the examples in this article, if you want to fully understand, please check the original text. To learn a programming language well, it is not enough to learn grammar, and it is necessary to gradually understand the CPU architecture, compiler/interpreter/virtual machine that the language relies on. Lignos This article, although not in-depth analysis of the implementation of Python, but for the beginner's help is very obvious, the original scholar has a certain experience, some problems can be done in-depth excavation, leading to the implementation of Python problems.

This article by the sentence Daquan www.zaojuzi.com finishing Release

Anti-patterns in Python programming

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.