Effective Python Memo Item 4 Write a helper function instead of a complicated expression

** 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.

Example of getting the contents of a URL query

Simple example

#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.

Let's write a helper function

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

Summary

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

Effective Python Memo Item 4 Write a helper function instead of a complicated expression
Effective Python memo Item 7 Use list comprehension instead of map and filter
Effective Python Memo Item 3
A python regular expression, or a memo of a match object
A memo of writing a basic function in Python using recursion
Effective Python memo Item 10 Enumerate from range
A memo of a tutorial on running python on heroku
Draw a graph of a quadratic function in Python
Get the caller of a function in Python
EP 4 Write Helper functions Instead of Complex Expressions
A memo connected to HiveServer2 of EMR with python
How to write a list / dictionary type of Python3
[Python] A memo to write CSV vertically with Pandas
I tried using Python (3) instead of a scientific calculator
A python lambda expression ...
python regular expression memo
How to develop in a virtual environment of Python [Memo]
Effective Python Memo Item 19 Give optional behavior to keyword arguments
Python> Read from a multi-line string instead of a file> io.StringIO ()
Effective Python Note Item 16 Consider returning a generator without returning a list
Create a function in Python
Write a kernel density function
[python] Value of function object (?)
[Python] Etymology of python function names
[Python] A memo of frequently used phrases (by myself) in Python scripts
Effective Python Memo Item 11 Use zip to process iterators in parallel
I tried to make a regular expression of "amount" using Python
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
I tried to make a regular expression of "time" using Python
Effective Python Note Item 15 Know how closures relate to function scope
I tried to make a regular expression of "date" using Python
A function that measures the processing time of a method in python
[Python3] Define a decorator to measure the execution time of a function
The idea of feeding the config file with a python file instead of yaml
[Python] A simple function to find the center coordinates of a circle