Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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
  • Move complex expressions into helper functions, especially if you nned to use the same logic repeatedly.
  • The if/else expression provides a more readable alternative to using Boolean operators like or and and in expressions

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])
    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])
        found = default
    return found
green = get_first_int(my_values, 'green')
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Help us understand the problem. What are the problem?