Python tips, how to simplify a lot of if... elif... else code?

In daily code, we always face a lot of if elif... Else conditional branch selection. To tell you the truth, the first thing I recommend in most cases is to write if honestly Elif, and try to extract the content under each branch into independent functions. Clear structure and clear intention are great convenience for writing and reading. However, in some special cases, other more elegant writing methods can be used to broaden the thinking of code writing.

Today, I read the code of EdgeDB[1] in Github and found that it is dealing with a large number of if elif... Else used a very clever decorator when judging. Let's see what this method looks like.

Today is double twelve. Suppose we want to make a function to judge the discount that can be obtained according to the user's level. Regular if elif... It's written like this:

def get_discount(level):
    if level == 1:
        "Mass calculation code"
        discount = 0.1
    elif level == 2:
        "Mass calculation code"
        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 'Grade error'
    return discount

As we all know, such a large number of if elif... The code is ugly and difficult to maintain. And there is a lot of code inside each if. This function will be pulled very long.

Some students know that they can rewrite this too long if judgment with a dictionary:

def parse_level_1():
    "Mass calculation code"
    discount = 0.1
    return discount

def parse_level_2():
    "Mass calculation code"
    discount = 0.2
    return discount

def parse_level_3():
    "Mass calculation code"
    discount = 0.3
    return discount

def parse_level_4():
    "Mass calculation code"
    discount = 0.4
    return discount

def parse_level_5():
    "Mass calculation code"
    discount = 0.5
    return discount

def parse_level_6():
    "Mass calculation code"
    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, 'Grade error')

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

@value_dispatch
def get_discount(level):
    return 'Grade error'

@get_discount.register(1)
def parse_level_1(level):
    "Mass calculation code"
    discount = 0.1
    return discount

@get_discount.register(2)
def parse_level_2(level):
    "Mass calculation code"
    discount = 0.2
    return discount

@get_discount.register(3)
def parse_level_3(level):
    "Mass calculation code"
    discount = 0.3
    return discount

@get_discount.register(4)
def parse_level_4(level):
    "Mass calculation code"
    discount = 0.4
    return discount

@get_discount.register(5)
def parse_level_5(level):
    "Mass calculation code"
    discount = 0.5
    return discount

@get_discount.register(6)
def parse_level_1(level):
    "Mass calculation code"
    discount = 3 + 2 - 5 * 0.1
    return discount


discount = get_discount(3)
print(f'For Level 3 users, the discount is:{discount}')

The operation effect is shown in the figure below:

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

So, this decorator_ How is dispatch implemented? The password is hidden in the source code [2] of the open source project EdgeDB. The core code is only more than 20 lines:

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

@get_discount.register(2)
@get_discount.register(3)
def parse_level_2(level):
    "Mass calculation code"
    discount = 0.2
    return discount

The operation effect is shown in the figure below:

summary

This code can only implement equal queries at present. But in fact, as long as the code is slightly modified, we can judge greater than, less than, greater than or equal to, less than or equal to, not equal to, in and so on. If you are interested, please leave a message at the bottom of the article.

Welcome to pay attention. Here we have a 100 day introductory practical course written by ourselves, a variety of interesting programming practices, a variety of learning materials, and a large group of lovely friends to discuss with each other.

 

Keywords: Python Back-end

Added by Jaguar on Tue, 14 Dec 2021 05:15:17 +0200