Python code optimization and tips (2)

Source: Internet
Author: User

Python code optimization and tips (2)

Overview
Here we will record some of the details and code optimization problems I encountered during the development process, and hope to share them with you.

Skillful 1. Obtain command line Output Using Python code

Here we can use Popen and PIPE in the subprocess module.
For example, if you have the following code, you can try to capture the text output from the console:

from subprocess import Popen, PIPElabel = "Hello, Shell."print(label)f = Popen(("python", "catch_output.py"), stdout=PIPE).stdoutprint("Catch Output: {0}".format(f.readline()))

In the above code, we can print our own console output, as well as the output information obtained by capturing the output. As follows:

Hello, Shell.Catch Output: Hello, Shell.
2. Do not use the expression as the default parameter of the function.

There is a basic and important feature in Python, that is, in python functions, we can specify a default value for the parameter. However, this is a small trap. For new users, this may cause frequent troubles. For example, we compile python code as follows:

def test_args(array=[]):    array.append("Bob")    return array

In the above Code, normally, there is no problem, because it can indeed print"[Bob]". However, the problem lies in our repeated calls. What do you say? The preceding test_args () method is called three times. The printed result is:

['Bob']['Bob', 'Bob']['Bob', 'Bob', 'Bob']

WTF!
How can this happen? Because,Optional parameter default value settings will only be executed once in Python.
How to understand it? It is very simple, that is, when the default value of our parameter is defined only for this function and the value of this parameter is not passed during function call, to assign a value to the default value.
The Code is as follows:

def test_args(array=None):    if array is None:        array = []    array.append("Bob")    return array
3. Specify the parameters of the exception block.

In python2.x, we know that you can use commas to specify exception parameters. As follows:

def fun():    try:        print("Hello, Exception")    except Exception, e:        print(e)    pass

However, in python3.x, this writing method has a syntax error. However, both python2.x and python3.x can be used.As. As follows:

def fun():    try:        print("Hello, Exception")    except Exception as e:        print(e)    pass

Therefore, it is best to use projects that may have version differencesAsTo specify parameters.

4. Change the list when traversing the list

Under normal circumstances, it is difficult for us to modify the list during list traversal. This rule is not only applicable to Python, but also exists in Java. For example, the following statement throws some exceptions.

def test_list_modify():    a = [0, 1, 2, 3, 4, 5, 6, 7, 8]    odd = lambda x: bool(x % 2)    for i in xrange(len(a)):        if odd(a[i]):            a.remove(i)    print(a)

The above code will certainly throw an exception, as shown below:

Traceback (most recent call last):  File "E:/workspace/src/Python/Demo/SimpleDemo-python/test/test_demo.py", line 106, in 
  
       test_list_modify()  File "E:/workspace/src/Python/Demo/SimpleDemo-python/test/test_demo.py", line 76, in test_list_modify    if odd(a[i]):IndexError: list index out of range
  

The cause is also easy to find. In the above Code, we try to modify the length of the list, which will lead to the loop process, the subscript accessing the array will exceed the length of the Modified list. The above exception information is thrown.
However, we can use the elegant programming paradigm of the Python language. The modified code is as follows:

def test_list_modify():    a = [0, 1, 2, 3, 4, 5, 6, 7, 8]    odd = lambda x: bool(x % 2)    a[:] = [n for n in a if not odd(n)]    print(a)
5. Print JSON more elegantly

In Python, The json module provides a very good interface for printing json objects --Json. dumps ()
Of course, the json object is passed in json. dumps (), rather than the original json string. To convert the original json stringEleganceAnd we can perform secondary encapsulation.

Pass Json. loads ()Converts a json string into a json object. Json. dumps ()Print the json string elegantly.
import jsonjson_data = "{\"status\": \"OK\", \"count\": 2, \"results\": [{\"age\": 27, \"name\": \"Oz\", \"lactose_intolerant\": true}," \            " {\"age\": 29, \"name\": \"Joe\", \"lactose_intolerant\": false}]}"def parser():    json_obj = json.loads(json_data)    show(json_obj)    passdef show(json_obj):    print(json.dumps(json_obj, indent=4))    passif __name__ == '__main__':    parser()    pass

The output is as follows:

6. _ init _. py

Sometimes we need to import a lot of content from other modules to a custom module, which will make the Code look bloated. However, we can solve this problem through the _ init _. py file. Put the code of the import module in the _ init _. py file, and then import all the content of the _ init _. py module into the target file.
The following code is available in _ init _. py:

import osimport timeimport datetime as date

The call code in the test file is as follows:

from __init__ import *print(time.ctime())print(date.date.day)print(os.system("python test_init.py"))

You can also choose to import data one by one as follows:

from __init__ import sysfrom __init__ import getoptfrom __init__ import packfrom __init__ import pehelpfrom __init__ import PEParserfrom __init__ import Signature
 

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.