Functional Programming in Python 🐍

About me

Riccardo aka @entropiae

Python in the streets
Erlang/Elixir (currently) in the sheets

Functional programming? 🤔

(almost) every developer has its own idea about functional programming.

First-class functions
Higher-order functions
Recursion instead of iteration

Focus on Tail Call Optimization

(not available in Python 😥)

Immutable data structures
Lazy evaluation
                            len([1, 1/0, '3']) == 3
                        
Emphasis on what is done, not on how is done

Ok ok, functions.

(Mathematical) functions
Pure functions

No side effects

Perfectly pure, almost useless

Practicality beats purity.

Referential transparency

Memoization

No order constraint

Full support for Multi{core, cpu, node} archs

Compiler optimization

Python as a functional programming language?

Python is not, by design, a FP language
However..

..coz everything is an object..

..we have first-class functions! 🎉

1994: higher-order functions were introduced in Python
map: transform a collection
map(lambda x: x + 1, [1, 2, 3]) == [2, 3, 4]
filter: remove elements from a collection
filter(lambda x: x % 2 == 0, [1, 2, 3]) == [2]
reduce: recursively apply an operation on a collection
reduce(lambda x, y: x + y, [1, 2, 3]) == 6

The cornestone of higher-order functions

map() and filter() could be replaced with a list comprehension

There should be one - and preferably only one - obvious way to do it.

GvR doesn't like them 😕

It was proposed to remove them from Python 3
More functions were build on these building blocks

functools, itertools