** Notes on Effective Python ** Item 4: Write helper functions instead of complex expressions
** Write a helper function because writing a complex expression in a single sentence will reduce readability ** If you feel like it, python puts a tremendous amount of syntax in one sentence, but it becomes very difficult to read, so you should provide a helper function to improve readability.
#Get arguments from url query
from urllib.parse import parse_qs
my_values = parse_qs('red=5&blue=0&green=',
keep_blank_values=True)
print('red: ', my_values.get('red'))
print('green: ', my_values.get('green'))
print('opacity: ', my_values.get('opacity'))
>>>
red: ['5']
green: ['']
opacity: None
⇒ When there is no value, it is better to unify to zero
#Compare before and after an expression using the or operator
red = my_values.get('red', [''])[0] or 0
green = my_values.get('green', [''])[0] or 0
opacity = my_values.get('opacity', [''])[0] or 0
print('red: %r' % red)
print('green %r' % green)
print('opacity %r' % opacity)
>>>
red: '5'
green 0
opacity 0
I was able to do it, but it's hard to see. .. .. Moreover, there are times when you want to process numbers with mathematical formulas instead of character strings. So let's wrap it with int ()!
red = int(my_values.get('red', [''])[0] or 0)
print('red: %r' % red)
>>>
red: 5
It's pretty hard to see. Not many people can understand it at a glance. You don't have to fit that much in one line in the first place.
Let's judge the condition in an easy-to-understand manner with if / else
red = my_values.get('red', [''])
red = int(red[0]) if red[0] else 0
print('red: %r' % red)
>>>
red: 5
It's a little neat, but the if statement isn't clean If you write it with a strict if statement
red = my_values.get('red', [''])
if red[0]:
red = int(red[0])
else:
red = 0
print('red: %r' % red)
>>>
red: 5
It's transmitted, but it's hard to see again.
def get_first_int(values, key, default=0):
found = values.get(key,[''])
if found[0]:
found = int(found[0])
else:
found = default
return found
red = get_first_int(my_values, 'red')
print('red: %r' % red)
>>>
red: 5
Python has a lot of useful descriptions, but if you use it too much, it will remain readable. Write a lot of helper functions depending on the situation.
Recommended Posts