[Reprint] efficient Python programming skills

Source: Internet
Author: User
Document directory
  •  

I have been using python for many years, and even today I am still amazed at the cleanliness of the Code and its applicability to the dry programming principles. Over the years, I have learned a lot of tips and knowledge, most of which are obtained by reading popular open-source software such as Django, flask, and requests.

The skills I picked below are often ignored, but they can really help us in daily programming.

1. dictionary comprehensions and set comprehensions)
Most Python programmers know and use list comprehensions ). If you are not familiar with the concept of list comprehensions, a list comprehension is a more brief and concise method for creating a list.

>>> some_list = [1, 2, 3, 4, 5]>>> another_list = [ x + 1 for x in some_list ]>>> another_list[2, 3, 4, 5, 6]

Since Python 3.1 (or even Python 2.7), we can use the same syntax to create a set and dictionary table:

>>> # Set Comprehensions>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]>>> even_set = { x for x in some_list if x % 2 == 0 }>>> even_setset([8, 2, 4])>>> # Dict Comprehensions>>> d = { x: x % 2 == 0 for x in range(1, 11) }>>> d{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}

In the first example, a set with non-repeating elements is created based on some_list, And the set contains only an even number. In the dictionary table example, we create an integer between 1 and 10 with no duplicate keys and a Boolean value to indicate whether the key is an even number.

Another noteworthy thing here is the literal representation of the set. We can simply use this method to create a set:

>>> my_set = {1, 2, 1, 2, 3, 4}>>> my_setset([1, 2, 3, 4])

Instead of using the built-in function set ().

2. Count objects with counter.
This sounds obvious, but it is often forgotten. For most programmers, counting one thing is a very common task, and in most cases it is not very challenging-there are several ways to do this more easily.

The collections class library of Python has a built-in dict class subclass, which is dedicated to doing this:

 

>>> from collections import Counter>>> c = Counter('hello world')>>> cCounter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})>>> c.most_common(2)[('l', 3), ('o', 2)]

 

3. beautifully printed JSON
JSON is a very good form of data serialization and is widely used by various APIs and Web services. Using the built-in JSON processing in python can make the JSON string readable. However, when a large data is displayed as a long, continuous row, it's hard for people to watch with their eyes.

To make JSON data more friendly, we can use the indent parameter to output beautiful JSON data. This is particularly useful when interactive programming or logging in the console:

 

>>> import json>>> print(json.dumps(data))  # No indention{"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]}>>> print(json.dumps(data, indent=2))  # With indention{  "status": "OK",  "count": 2,  "results": [    {      "age": 27,      "name": "Oz",      "lactose_intolerant": true    },    {      "age": 29,      "name": "Joe",      "lactose_intolerant": false    }  ]}

 

Similarly, the built-in pprint module can make the output of other things more beautiful.

4. Create a one-time and fast small Web Service
Sometimes, we need to make some simple, basic RPC interaction between two machines or services. We want to use program B to call a method in program a in a simple way-sometimes on another machine. For internal use only.

I do not encourage the methods described here to be used in non-internal, one-time programming. We can use a protocol called XML-RPC (corresponding to this python Library) to do this.
The following is an example of using the simplexmlrpcserver module to create a fast small file read Server:

 

from SimpleXMLRPCServer import SimpleXMLRPCServerdef file_reader(file_name):    with open(file_name, 'r') as f:        return f.read()server = SimpleXMLRPCServer(('localhost', 8000))server.register_introspection_functions()server.register_function(file_reader)server.serve_forever()

 

Client:

import xmlrpclibproxy = xmlrpclib.ServerProxy('http://localhost:8000/')proxy.file_reader('/tmp/secret.txt')

In this way, we get a Remote File Reading tool without external dependencies and only a few lines of code (of course, there are no security measures, so we can only do this at home ).

5. the magical open-source community of Python
I have mentioned several things in the python standard library. If you have installed python, you can use it like this. For many other types of tasks, a large number of third-party libraries maintained by the Community are available for you.

The following list is a required condition for a user-friendly and robust open-source Library:

Good open-source libraries must...

  • Include a clear license statement that applies to your use cases.
  • Development and maintenance work is very active (or, you can participate in development and maintenance .)
  • It can be easily installed or repeatedly deployed using Pip.
  • There is a test suite with sufficient test coverage.

If you find a good library that meets your requirements, don't be embarrassed-you are welcome to donate code and help for most open-source projects-even if you are not a python expert.

Original article: http://www.aqee.net/improving-your-python-productivity/

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.