Home Backend Development Python Tutorial Introducing efficient programming techniques in Python

Introducing efficient programming techniques in Python

Apr 05, 2017 pm 01:36 PM

I've been programming in Python for many years, and even today I'm amazed at how clean the language can make code appear and how well it applies DRY programming principles. Over the years, I have learned a lot of tips and knowledge, most of which were obtained by reading popular open source software, such as Django, Flask, and Requests.

The techniques I have selected below are often overlooked by people, but they can really help us a lot in daily programming.

1. Dictionary comprehensions and Set comprehensions

Most Python programmers know and have used list comprehensions. If you're not familiar with the concept of list comprehensions - a list comprehension is a shorter, more concise way of 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]
Copy after login

Since Python 3.1 (and even Python 2.7), we can use the same syntax to create sets and dictionaries:

>>> # 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_set
set([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}
Copy after login

In the first example, we create a set with unique elements based on some_list, and the set only contains even numbers. In the example of the dictionary table, we created a key that is a non-repeating integer between 1 and 10, and the value is a Boolean type that indicates whether the key is an even number.

Another thing worth noting here is the literal representation of sets. We can simply create a collection using this method:

>>> my_set = {1, 2, 1, 2, 3, 4}

>>> my_set
set([1, 2, 3, 4])
Copy after login

There is no need to use the built-in function set().

2. Use Counter counting object when counting.

This sounds obvious, but is often forgotten. Counting something is a common task for most programmers, and in most cases not very challenging - here are a few ways to make it easier.

Python’s collections class library has a built-in subclass of the dict class, which is specially designed to do this kind of thing:

>>> from collections import Counter
>>> c = Counter('hello world')

>>> c
Counter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})

>>> c.most_common(2)
[('l', 3), ('o', 2)]
Copy after login

3. Beautifully print out JSON

JSON is a very good form of data serialization and is widely used by various APIs and web services today. Using Python's built-in json processing can make the JSON string readable to a certain extent, but when encountering large data, it appears as a long, continuous line, which is difficult for the human eye to view.

In order to make JSON data more friendly, we can use the indent parameter to output beautiful JSON. This is especially useful when programming interactively at the console or logging:

>>> 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
    }
  ]

}
Copy after login

Similarly, using the built-in pprint module can also make anything else print more beautifully.

4. Create a one-time, fast small web service

Sometimes, we need to do some simple, very basic RPC-like interactions 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. Internal use only.

I do not encourage the use of the methods described here for non-internal, one-off programming. We can use a protocol called XML-RPC (corresponding to this Python library) to do this kind of thing.

The following is an example of using the SimpleXMLRPCServer module to build a fast small file reading server:

from SimpleXMLRPCServer import SimpleXMLRPCServer

def 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()
Copy after login

Client:

import xmlrpclib
proxy = xmlrpclib.ServerProxy('http://localhost:8000/')

proxy.file_reader('/tmp/secret.txt')
Copy after login

In this way, we get a remote file reading tool, with no external dependencies and only a few lines of code (of course, without any security measures, so you can only do this at home).

5. Python’s amazing open source community

The several things I mentioned here are all in the Python standard library. If you have Python installed, you can already use it in this way. For many other types of tasks, there are a large number of community-maintained third-party libraries you can use.

The following list is what I consider necessary for a useful and robust open source library:

A good open source library must...
  • Include a clear permission statement that applies to your use case.


  • The development and maintenance work is active (or, you can participate in the development and maintenance of it.)


  • Can be easily installed or deployed repeatedly using pip.


  • Have a test suite with adequate test coverage.

If you find a good library that meets your requirements, don't be embarrassed - most open source projects welcome code donations and help - even if you are not a Python master.

Original link: Improving Your Python Productivity

The above is the detailed content of Introducing efficient programming techniques in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles