Python: functional programming

One year ago I’ve posted short note about imperative vs. functional approaches in python. Well, that one was incorrect 😉

The task was to get all unique tokens from several string separated by some delimiter.

regions_strs = (“Some, ST / More, HERE”, “Some, ST / More2, HERE2”)

So, result should be: (‘Some, ST’, ‘More, HERE’, ‘More2, HERE2’)

# 1. classic imperative solution
regions = set()
for s in regions_strs:
  for token in s.split(‘/’):

# 2. very bad still imperative ugly solution
regions = reduce(
  lambda regions_set, regions_str:
        lambda regions_set, region:
            regions_set | set((region.strip(),)),

# 3. really functional way
regions = iunique(token.strip() for token in
    itertools.chain(*(s.split(‘/’) for s in regions_strs))

where iunique is a special generator that used as filter for abstract iterator. It’s a pure tool like those from itertools and collections standard python toolsets.

def iunique(iterable, key=lambda x: x):
  “”” unique filter “””
  seen = set()
  for elem, ekey in ((e, key(e)) for e in iterable):
    if ekey not in seen:
      yield elem

2’nd implementation is still imerative because it provides the result as data. 3-rd approach provides iterator instead. So, real functional programming way is providing not data result but function. Result is something that can be evaluated/calculated to obtain actual result.

Besides, 2-nd code operates by data in its implementation and 3-rd functional code uses only source data (tuple of source strings and separator).

2-nd solution uses functional sugar like lambda, reduce, split, but those ones only made code ugly and huge. Keep in mind, the code should be as small as possible and very clear.

Python has powerful functional tools like iterators and generators; standard packages itertools and collections. So, it’s ok to do some functional programming in python that would be clear, correct and robust.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: