Python tips! How to simplify a lot of if…elif…else code?

5b0d1b9923c58353a1f66607087c5b62.png

Flowering cat language: In daily code, we always face a lot of if...elif...else conditional branch selection problems. To be honest, my first recommendation in most cases is to write if...elif honestly, and try to extract the content under each branch into an independent function. The structure is clear and the intention is clear, which is very convenient for writing and reading. However, in some special cases, other more elegant writing methods can be used, such as "How to elegantly judge the level of a number without using the if-elif statement" we shared before ? ", and this article to be shared today, can broaden the thinking of code writing.

Reading the code of EdgeDB[1] on Github today, I found that it if...elif...elseuses a very clever decorator when dealing with a large number of judgments. Let's take a look at what this method looks like.

It just so happens that today is Double Eleven. Suppose we want to create a function to judge the discounts that users can get based on their grades. The usual if ... elif...way of writing is this:

def get_discount(level):
    if level == 1:
        "大量计算代码"
        discount = 0.1
    elif level == 2:
        "大量计算代码"
        discount = 0.2
    elif level == 3:
        discount = 0.3
    elif level == 4:
        discount = 0.4
    elif level == 5:
        discount = 0.5
    elif level == 6:
        discount = 3 + 2 - 5 * 0.1
    else:
         return '等级错误'
    return discount

Everyone knows that such a large amount of if ... elif...code is very ugly and difficult to maintain. And inside each if there is a lot of code. This function will be stretched very long.

Some students know that you can use a dictionary to rewrite this too long if judgment:

def parse_level_1():
    "大量计算代码"
    discount = 0.1
    return discount

def parse_level_2():
    "大量计算代码"
    discount = 0.2
    return discount

def parse_level_3():
    "大量计算代码"
    discount = 0.3
    return discount

def parse_level_4():
    "大量计算代码"
    discount = 0.4
    return discount

def parse_level_5():
    "大量计算代码"
    discount = 0.5
    return discount

def parse_level_6():
    "大量计算代码"
    discount = 3 + 2 - 5 * 0.1
    return discount

discount_map = {
 1: parse_level_1,
  2: parse_level_2,
  3: parse_level_3,
  4: parse_level_4,
  5: parse_level_5,
  6: parse_level_6,
}

discount = discount_map.get(level, '等级错误')

But the method I learned today is simpler than using a dictionary. Let's first look at its effect:

@value_dispatch
def get_discount(level):
    return '等级错误'

@get_discount.register(1)
def parse_level_1(level):
    "大量计算代码"
    discount = 0.1
    return discount

@get_discount.register(2)
def parse_level_2(level):
    "大量计算代码"
    discount = 0.2
    return discount

@get_discount.register(3)
def parse_level_3(level):
    "大量计算代码"
    discount = 0.3
    return discount

@get_discount.register(4)
def parse_level_4(level):
    "大量计算代码"
    discount = 0.4
    return discount

@get_discount.register(5)
def parse_level_5(level):
    "大量计算代码"
    discount = 0.5
    return discount

@get_discount.register(6)
def parse_level_1(level):
    "大量计算代码"
    discount = 3 + 2 - 5 * 0.1
    return discount


discount = get_discount(3)
print(f'等级3的用户,获得的折扣是:{discount}')

The running effect is shown in the figure below:

f67b435276e480942e374d336d6b21f5.png

Writing in this way is more intuitive than using a dictionary, and if ... elif...more concise than using it directly.

So, how is this decorator value_dispatchimplemented? The password is hidden in EdgeDBthe source code [2] of this open source project, and the core code is only more than 20 lines:

7904261c2c59a1aa04171bc972c43f6c.png

And, it is also possible to implement or query. For example, when the user level is 2 or 3, the discount is 0.2, then the code can be written as:

@get_discount.register(2)
@get_discount.register(3)
def parse_level_2(level):
    "大量计算代码"
    discount = 0.2
    return discount

The running effect is shown in the figure below:

de4446f561684b2497e36ae930f76182.png

Its code currently only implements equality queries. But in fact, as long as this code is slightly modified, we can realize greater than, less than, greater than or equal to, less than or equal to, not equal to, and inso on. If you are interested, please leave a message below the article, and we will talk about how to modify this code tomorrow to achieve more logical judgments.

references

[1] EdgeDB: https://github.com/edgedb/edgedb

[2] Source code: https://github.com/edgedb/edgedb/blob/master/edb/common/value_dispatch.py

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

Annual blockbuster copywriting

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

Guess you like

Origin blog.csdn.net/cainiao_python/article/details/121782041#comments_27650297