about 3 years ago

Write Helper Functions Instead of Complex Expressions

這個條款其實在講怎麼寫可讀性佳的程式,和 Python 關係不大。

from urllib.parse import parse_qs
my_values = parse_qs('red=5&blue=0&green=',
                     keep_blank_values=True)
# my_values: {'red': ['5'], 'green': [''], 'blue': ['0']}

red = my_values.get('red', [''])
red = int(red[0]) if red[0] else 0
green = my_values.get('green', [''])
green = int(green[0]) if green[0] else 0
opacity = my_values.get('opacity', [''])
opacity = int(opacity[0]) if opacity[0] else 0
print('Red:     %r' % red)
print('Green:   %r' % green)
print('Opacity: %r' % opacity)

很明顯的違反 DRY,而且可讀性低,所以共通的程式碼寫成函式

def get_first_int(values, key, default=0):
    found = values.get(key, [''])
    if found[0]:
        found = int(found[0])
    else:
        found = default
    return found

green = get_first_int(my_values, 'green')
print('Green:   %r' % green)
← Effective Python 心得筆記: Item 3 Effective Python 心得筆記: Item 5 →
 
comments powered by Disqus