Help us understand the problem. What is going on with this article?

EP 4 Write Helper functions Instead of Complex Expressions

More than 3 years have passed since last update.
  • 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])
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')
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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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