[PYTHON] EP 4 Write Helper-Funktionen anstelle komplexer Ausdrücke

  • 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-Funktionen anstelle komplexer Ausdrücke
EP 23 Akzeptieren Sie Funktionen für einfache Schnittstellen anstelle von Klassen
Effektives Python-Memo Element 4 Schreiben Sie eine Hilfsfunktion anstelle eines komplizierten Ausdrucks
EP 16 Generator in Betracht ziehen, anstatt Listen zurückzugeben
EP 7 Listenverständnisse anstelle von Karte und Filter verwenden