Python insights-How to improve code quality

Source: Internet
Author: User

The previous days with Python based on Prometheus developed a vsphere volume volume monitoring exporter, so with the Vsphere API (Pyvmomi) interface in the dealings, During the development process you will find that the Pyvmomi interface returns many types of objects, and you may need to iterate through multiple layers when you take one of the objects. That prompted me to write this article, documenting some of the experiences in using Python to move bricks. If there is any mistake, please correct me.

650) this.width=650; "src=" http://p3.pstatp.com/large/3f2d0000b47b43cd60e1 "style=" Margin:1em auto;padding:0px; Border:0px;font-style:inherit;font-variant:inherit;font-weight:inherit;font-size:inherit;line-height:inherit; Font-family:inherit;vertical-align:baseline, "alt=" 3f2d0000b47b43cd60e1 "/>

python inside the so-called high-quality code, I understand the main is two aspects. One is to write a Python-style code, known as the pythonic; Two is the code of execution efficiency . The efficiency of Python's execution has always been criticized, I admit, but I agree with the saying that "the programming language itself is not good or bad, the key is the use of the user is appropriate." The

Here is a summary of some of the common ways to improve code quality in Python programming:

    1. Assigning values to variables

In [all]: A, B = 10, 50 # assignment written on one line in [[]: aout[12]: 10In []: bout[13]: 50In []: A, B = B, a # A, B interchange in []: aout[15]: 5 0In [+]: bout[16]: 10

Try to avoid using intermediate variables to increase overhead when exchanging variables.

2. List deduction for improved efficiency and readability

Create a new list as follows:

in [+]: [N for N in Range]]out[17]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

On the other hand, list derivation can also be abused. The general rule is to create a new list with only a list deduction and keep it as short as possible . If the list derives more than two lines of code, you might want to consider whether you need to rewrite it with a for loop. As with writing articles, and there is no hard rules, this degree need to grasp their own.

3. Iteration of lists and dictionaries

list uses enumerate () to get the index and value of the list, and the dictionary uses the Iteritems method to get the index and value.

in [+]: L1 = [n for n in range]]in [+]: for K, V in Enumerate (L1): ....: Print K, v....:0 9In []: Dict1 = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}in []: dict1out[24]: {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}in [+]: for K, V in Dict1.iteritems (): ....: Print K, V....:A 1c 3b 2d 4

4. Conditional assignment using three-dimensional expressions

Ternary expressions allow you to quickly judge with a simple line, rather than using complex multiline if statements, making your code simple and maintainable.

in [+]: 1 if 5>3 else 0out[26]: 1In [+]: 1 if 5>8 else 0out[27]: 0

Give an example of using list derivation and ternary expressions in real production:

Dc_list = [Datacenter for datacenter in Root_folder.childentity if Isinstance (Datacenter, vim. Datacenter)]

This generates a list named Dc_list, first traversing the datacenter in "root_folder.childentity" and then judging whether the datacenter is a "vim." Datacenter "instance, if true, is added to the Dc_list list and eventually returns the Datacenter list.

5. Use with auto-close resource

You should close them immediately after the file operation is complete, because open files will not only consume system resources, but may also affect the operation of other programs or processes, and even cause user expectations to be inconsistent with the actual operation results.

In [5]: With open (' 111.py ', ' RB ') as file: ...: For line in file: ...: print line...:#!/usr/bin/env python#-*-coding:utf-8 -*-print "name is%s"% __file__

6. Use yield

Here is an example of a Fibonacci sequence:

In [8]: Def FAB (n):..: A, b = 0, 1 ...: For i in Xrange (n): ...: Yield b ..., a, B = B, A + b...:in [9]: Fab () out[9]: < Generator Object fab at 0x1092975a0>in [ten]: for n in Fab: ....: Print n....:11235813213455891442333776109871597258 441816765

It can be seen that a function with yield is a generator, which, unlike the normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.

7. Reduce the calculation of internal execution of the loop

The key to optimizing the Python loop is to reduce the amount of work that Python performs within the loop.

in [+]: A = range (10000) in [+]: size_a = Len (a) in [+]:%timeit-n-i in a:k = Len (a) at loops, Best of 3:658 μs per Loopin [in]:%timeit-n-i in a:k = size_a1000 loops, Best of 3:304μs per loop

8. String connections take precedence over "join" instead of "+"

In [all]: letter = [' A ', ' B ', ' C ', ' d ']in [+]: print '. Join (letter) ABCD

9. None Type Judgment

Do not use ' = = ' in the form of none:

if foo = = None:do_something ()

Correct usage:

If not foo:do_something ()

650) this.width=650; "src=" http://p1.pstatp.com/large/3f290002e2c8e4c5f747 "style=" Margin:1em auto;padding:0px; Border:0px;font-style:inherit;font-variant:inherit;font-weight:inherit;font-size:inherit;line-height:inherit; font-family:inherit;vertical-align:baseline; "alt=" 3f290002e2c8e4c5f747 "/>

10. "Premature optimization is the root of all evils"

Finally, I have to mention this sentence, borrowing the interpretation of others:

Make it work.make it right.make it Fast. Don't skip the front two straight to the third one!

This article is from the "XUJPXM" blog, make sure to keep this source http://xujpxm.blog.51cto.com/8614409/1971832

Python insights-How to improve code quality

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.