[PYTHON] EP 4 Write Helper functions Instead of Complex Expressions

  • Python's syntax makes it all too easy to write single-line expressions taht are overly complicated and difficult to read

Effective Python

Let's thinke the situation where we want to parse the first value of the url parameters.

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

>>> print("Red", my_values.get('red'))
Red ['5']
>>> print("Green", my_values.get('green'))
Green ['']
>>> print("Opacity", my_values.get('opacity'))
Opacity ['']

We want to ensure that value should be integer and if it does not present in dictionaly, it returns 0.

red = int(my_values.get('red',[''])[0] or 0)

We can do this way. But it lacks readablity.

green = my_values.get('green', [''])
if green[0]:
    green = int(green[0])
else:
    green = 0

This flow is reused in other place and giving name for this process improves readablity. Therefore: a helper function is the way to go.

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

Recommended Posts

EP 4 Write Helper functions Instead of Complex Expressions
EP 23 Accept Functions for Simple Interfaces Instead of Classes
Effective Python Memo Item 4 Write a helper function instead of a complicated expression
EP 16 Consider Generator Instead of Returning Lists
EP 7 Use List Comprehensions Instead of map and filter