90% of the veterans don't know that Python exceptions can be written so elegantly!

604e823e29f5ecd58192b0cf9e12be0d.png

bb156e560f11e79ea2da82b40ebfcd0c.png

When writing programs, we often encounter program exceptions. At this time, we have to deal with these exceptions to ensure the robustness of the program.

There are several versions of exception handling, which one do you usually do?

e813b78479774487c027b0ebad011713.png


irresponsible version

In this case, do not do anything, let the program report an error, resulting in program interruption.

For simple programs, it's fine to do this, the big deal is that I'll fix the problem and run it again. But if it is a complex system, it will be very troublesome. Maybe you block the operation of the system with an exception, which will bring catastrophic consequences.

Simple processing version

The simple processing version is to add exception capture, record the log when an exception occurs, and locate the exception through the log.

def do_something():
    pass
def log_error(xxx):
    pass

try:
   do_something()
except:
    log_error(xxxx)

Improved handling version

Improvements have been made to the simple processing version to increase the number of retries. This is more common in crawler programs. The first request times out, and the request may be successful after a while, so retrying a few times may eliminate the exception.

attempts = 0
success = False
while attempts < 3 and not success:
    try:
        do_something()
        success = True
    except:
        attempts += 1
        if attempts == 3:
            break

But this is still not elegant, you may have to hard code this kind of retry in many places, and the program will look messy.

cc5212d83fcda7f06d3fbe72f2a39eab.png


Today I will introduce a third-party module - retrying. It is an elegant solution to exception retries in a program.

installation and use

Install

The install command is still pretty bland:

pip install retrying

use

Let me introduce to you the parameters that can be used in this decorator function.

life is long so add oil

retrying provides a decorator function retry, the decorated function will be re-executed if it fails to run. By default, it will always retry when an error is reported.

import random
from retrying import retry

@retry
def do_something_unreliable():
    if random.randint(0, 10) > 1:
        print("just have a test")
        raise IOError("raise exception!")
    else:
        return "good job!"

print(do_something_unreliable())

Running this program, you can see that the number of times the sentence "just have a test" is printed is different each time. This is because our program will print and throw an exception whenever the random integer is greater than 1. But since we have the decorator function retry, the method will be re-executed when an exception occurs, until the random integer is greater than 1, and "good job!" will be printed.

Don't be too stubborn

This endless retry is a waste of life and resources. We want to build green homes, so let's add some restrictions:

# 最大重试次数
@retry(stop_max_attempt_number=5)
def do_something_limited():
    print("do something several times")
    raise Exception("raise exception")

do_something_limited()
Cherish the limited time

An inch of time is worth an inch of gold, and an inch of gold cannot buy an inch of time. We want to cherish limited time, so let's add a time limit to our retry:

# 限制最长重试时间(从执行方法开始计算)
@retry(stop_max_delay=5000)
def do_something_in_time():
    print("do something in time")
    raise Exception("raise exception")

do_something_in_time()
Stop and admire the scenery along the way

Life has been in a hurry for decades. Don't run all the way and forget to appreciate the beautiful scenery along the road. Sometimes we need to take a moment to appreciate the beautiful scenery along the way:

# 设置固定重试时间
@retry(wait_fixed=2000)
def wait_fixed_time():
    print("wait")
    raise Exception("raise exception")

wait_fixed_time()
set a limit on failure

Although we need the resilience of repeated defeats and battles, there must be a limit to failure, and we cannot spend a lifetime in failure:

# 设置重试时间的随机范围
@retry(wait_random_min=1000,wait_random_max=2000)
def wait_random_time():
    print("wait")
    raise Exception("raise exception")

wait_random_time()
some people are worth the wait

In the vast sea of ​​people, I just want to wait for the right person:

# 根据异常重试
def retry_if_io_error(exception):
    return isinstance(exception, IOError)

# 设置特定异常类型重试
@retry(retry_on_exception=retry_if_io_error)
def retry_special_error():
    print("retry io error")
    raise IOError("raise exception")

retry_special_error()

We define a function ourselves, judge the exception type, and then pass the function as a parameter to the decorated function retry. If the exception type matches, it will retry.

Some results are what we want to see

Life is not smooth sailing, and sometimes we encounter setbacks that may be what we want in the first place:

# 通过返回值判断是否重试
def retry_if_result_none(result):
    """Return True if we should retry (in this case when result is None), False otherwise"""
    # return result is None
    if result =="111":
        return True


@retry(retry_on_result=retry_if_result_none)
def might_return_none():
    print("Retry forever ignoring Exceptions with no wait if return value is None")
    return "111"

might_return_none()

Here we define a function that determines the return value, and then pass this function as a parameter to the retry decorator. When the result returned is "111", the might_return_nonefunction .

Life is colorful, not monotonous

Our lives are colorful and never monotonous. Therefore, the above parameters can be used in any combination, and it is not limited to use only one at a time. For example, you can limit the retry IOErrorwhen , and the number of retries is up to 5 times.

Summarize

Life can't be repeated, but Python can try again!

I have retryingdedicated the use of this decorator function to you without reservation, so hurry up and use it!

Interested students can quickly join our planet

3 weeks zero basic introduction provides 10 lessons

12 interesting practical projects throughout the year including source code,

Reward outstanding Top3 students every month to send books

Professional Q&A group, nanny-style teaching by Dachang teachers

If you are not satisfied, feel free to refund within three days! 88 a year, now 16 yuan off

da77be60762317172224c4dd0b4537ae.png

Scan the code to join, get started with zero basics in 3 weeks

推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

The year's hottest copy

Click to read the original text to see 200 Python cases!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326841902&siteId=291194637