官术网_书友最值得收藏!

  • The Python Workshop
  • Andrew Bird Dr Lau Cher Han Mario Corchero Jiménez Graham Lee Corey Wade
  • 640字
  • 2021-06-11 12:51:32

Helper Functions

A helper function performs part of the computation of another function. It allows you to reuse common code without repeating ourselves. For instance, suppose you had a few lines of code that printed out the elapsed time at various points in a function:

import time

def do_things():

    start_time = time.perf_counter()

    for i in range(10):

        y = i ** 100

        print(time.perf_counter() - start_time, "seconds elapsed")

    x = 10**2

    print(time.perf_counter() - start_time, "seconds elapsed")

    return x

   

do_things()

You should get the following output:

Figure 3.29: Timing our helper functions

The print statement is repeated twice in the preceding code, and will be better expressed as a helper function, as follows:

import time

def print_time_elapsed(start_time):

    print(time.perf_counter() - start_time, "seconds elapsed")

def do_things():

    start_time = time.perf_counter()

    for i in range(10):

        y = i ** 100

        print_time_elapsed(start_time)

    x = 10**2

    print_time_elapsed(start_time)

    return x

Don't Repeat Yourself

The preceding example encapsulates the Don't Repeat Yourself (DRY) programming principle. In other words, "Every piece of knowledge or logic must have a single, unambiguous representation within a system." If you want to do the same thing multiple times in your code, it should be expressed as a function, and called wherever it is needed.

Exercise 54: Helper Currency Conversion

In this exercise, you will take a function that computes the total USD for a transaction and use a helper function to apply the DRY principle. You also want to add an optional margin into the currency conversion that should default to 0:

def compute_usd_total(amount_in_aud=0, amount_in_gbp=0):

    total = 0

    total += amount_in_aud * 0.78

    total += amount_in_gbp * 1.29

    return total

compute_usd_total(amount_in_gbp=10)

You should get the following output:

12.9

  1. Create a currency conversion function with an optional margin:

    def convert_currency(amount, rate, margin=0):

         return amount * rate * (1 + margin)

  2. Modify the original function to use the helper function:

    def compute_usd_total(amount_in_aud=0, amount_in_gbp=0):

        total = 0

        total += convert_currency(amount_in_aud, 0.78)

        total += convert_currency(amount_in_gbp, 1.29)

        return total

  3. Check the result:

    compute_usd_total(amount_in_gbp=10)

    You should get the following output:

    12.9

  4. Suppose that the business has decided to add a 1% margin for the conversion of the GBP component. Modify the function accordingly:

    def compute_usd_total(amount_in_aud=0, amount_in_gbp=0):

        total = 0

        total += convert_currency(amount_in_aud, 0.78)

        total += convert_currency(amount_in_gbp, 1.29, 0.01)

        return total   

  5. Check the result:

    compute_usd_total(amount_in_gbp=10)

    You should get the following output:

    13.029

Note that it's possible to get ahead of yourself when applying the DRY principle in writing reusable code. In the currency example, if our application really did just require converting currency once, then it probably shouldn't be written as a separate function. It may be tempting to think that generalizing our code is always good because it insures us against the possibility of needing to repeat the same code later; however, this attitude is not always optimal. You can end up spending a lot of time writing more abstract code than is necessary, and, often, this code can be less readable and may introduce unnecessary complexity to our codebase. Typically, the time to apply the DRY principle is when you find yourself writing the code for the second time.

主站蜘蛛池模板: 都江堰市| 静安区| 微山县| 吉首市| 明溪县| 富阳市| 阜平县| 进贤县| 商洛市| 固阳县| 漳州市| 金平| 博罗县| 太仓市| 灵山县| 丹江口市| 恩施市| 孝昌县| 马山县| 长汀县| 鞍山市| 鄂尔多斯市| 西林县| 鄂托克前旗| 三门县| 白城市| 乐清市| 榆林市| 松滋市| 孟村| 蛟河市| 阿巴嘎旗| 泸定县| 伊金霍洛旗| 东宁县| 富平县| 汉源县| 梨树县| 开封县| 前郭尔| 崇信县|