Teach you 5 ways to write elegant Python code easily

In Python, elegant code is generally called Pythonic. In my understanding, the so-called Pythonic is to write concise and beautiful code in Python.

Today I will share with you 5 concise and beautiful codes. I believe you will have a different understanding of how to write Python after reading this article.

  • Make good use of built-in functions
  • Reasonable use of data structure
  • Reasonable use of Python's advanced concurrency tools
  • Clever use of decorators to simplify code
  • Design patterns in Python
1. Make good use of built-in functions

1.1 enumerate type

Enumerate is a class, but it is as easy to use as a function. Not using enumerate may be the easiest place for new Python developers to be complained. Enumerate is actually very simple. It receives an iterable object and returns a combination of index and elements in the iterable object.

When not using enumerate

from __future__ import print_function
L = [ i*i for i in range(5) ]
index = 0
for data in L:
    index += 1
    print(index, ':', data)

Correct use of enumerate posture:

L = [ i*i for i in range(5) ]
for index, data in enumerate(L, 1):
    print(index, ':', data)

Not using enumerate requires 4 lines of code, and using enumerate only requires 2 lines of code. If you want to write code concisely and beautifully, you must always remember: under the premise of ensuring code readability, the less code the better .

1.2 any

Among the built-in functions, functions like any and all are known to everyone, and they think they are very simple, but they can’t be remembered when they are used. Let's look at a concrete example.

Take tuples as an example, as shown below:

(('t', 0, 'PRIMARY', 1, 'id', 'A', 0, None, None, '', 'BTREE', '', ''),)

We now need to traverse a two-dimensional tuple, and then determine whether there is a record whose Non_unique is 0 and the Null column is not YES. After understanding the specific implementation in detail, we wrote the following code:

 def has_primary_key():
     for row in rows:
         if row[1] == 0 and row[9] != 'YES':
             return True
    return False

If we use the any function, the code will be shorter.

def has_primary_key():
    return any(row[1] == 0 and row[9] != 'YES' for row in rows):
2. Make good use of built-in functions

Let's look at a similar example, get elements and delete:

L = [1, 2, 3, 4]
last = L[-1]
L.pop()
print(last)  # 删除元素
print(L)  # 最终元素
-----result--------
4
[1, 2, 3]

Here we do it again. When calling the L.pop() function, it will return the number we need to pop. In fact, we can do this:

L = [1, 2, 3, 4]
last = L.pop()
print(last)  # 删除元素
print(L)  # 最终元素
-----result--------
4
[1, 2, 3]
3. Reasonably use Python's advanced concurrency tools

Many times, we need to use concurrent programming instead of manually starting a thread or process by ourselves. You can use the concurrency tools provided by Python. The built-in map runs in a single thread. If network requests or a large number of cpu calculations are involved, the speed will be relatively slower, and concurrent maps appear as follows:

import requests
from multiprocessing import Pool
def get_website_data(url):
    r = requests.get(url)
    return r.url
def main():
    urls = ['http://www.google.com',
    'http://www.baidu.com',
    'http://www.163.com']
    pool = Pool(2)
    print(pool.map(get_website_data, urls))
main()

In order to be compatible with threads, the module also provides multiprocessing.dummy to provide the implementation of thread pool, as shown below:

from multiprocessing.dummy import Pool

Using Pool, we can quickly switch back and forth between thread pool and process pool. Most importantly, using advanced concurrency tools is not so error-prone.

4. Cleverly use decorators to simplify the code

Decorators are probably the most asked knowledge in Python interviews. The reason why it appears so frequently is because decorators are indeed a good thing.

For example, we have two modules. Module A needs to send a message to module B. Module B checks the parameters sent by module A. If there is no problem, it will proceed. For the operation of checking parameters, if we use a decorator , The code will look like this:

import inspect
import functools
def check_args(parameters):
    """check parameters of action"""
    def decorated(f):
        """decorator"""
        @functools.wraps
        def wrapper(*args, **kwargs):
        """wrapper"""
            func_args = inspect.getcallargs(f, *a
            msg = func_args.get('msg')
            for item in parameters:
                if msg.body_dict.get(item) is Non
                return False, "check failed,
            return f(*args, **kwargs)
        return wrapper
    return decorated
    
使⽤的时候:

class AsyncMsgHandler(MsgHandler):
  @check.check_args(['ContainerIdentifier', 'MonitorSecretKey','InstanceID','UUID'])
  def init_container(self, msg):
    pass
5. Design patterns in Python

Those who are familiar with Python modules will know that in Python, the module is initialized only once, all variables belong to a certain module, and the import mechanism is thread-safe. Therefore, the module itself is a natural singleton implementation. Therefore, we can implement the singleton mode with the help of modules.

The following example creates a function to return a dictionary containing currency exchange rates. This function can be called multiple times. However, in most cases, the exchange rate data is only obtained once, and there is no need for each time. Get it once when calling.

def get():
    if not get.rates:
        _URL = 'http://www.bankofcanada.ca/stats/
        with urllib.request.urlopen(_URL) as file
            for line in file:
            # get.rates[key] = float(data)
            pass
    return get.rates
get.rates = {}

In this code, even though there is no class introduced, we still make the exchange rate data "singleton data value". As you can see, in Python, singletons can be implemented directly using modules, which is very simple.

Recommended reading

For more exciting content, follow the WeChat public account "Python learning and data mining"

In order to facilitate technical exchanges, this account has opened a technical exchange group. If you have any questions, please add a small assistant WeChat account: connect_we. Remarks: The group is from CSDN, welcome to reprint, favorites, codewords are not easy, like the article, just like it! Thanks
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_38037405/article/details/108429099