Pycon NL: How functional programming can help you write better python code - Arjan Egges

Tags: pycon, python

(One of my summaries of the one-day Pycon NL conference in Utrecht, NL).

You might start with some simple python code. Just a few functions. It grows and grows. Now… how do I structure this? You start looking at complex enterprise code? Object oriented programming? Software patters? Why not look at functional programming?

Arjan showed some simple code with a class in it. A customer wish resulted in a subclass with some custom behavior. But if you’d change the original class, you’d also change the subclass’s behaviour. Brittle. Often, subclassing is discouraged. The “rust” language even doesn’t include subclassing.

With some live coding, he re-wrote the class to functions. You can pass functions as variables in python.

Another trick is to use “closures”: a function that builds and returns a function:

def is_elegible(cutoff_age: int = 50) -> Callable[[...]]:
    def is_eligble_function(customer, cutoff_age):
        return customer.age > cutoff_age
    return is_eligble_function

You can do this more elegantly with from functools import partial. That’s a decorator you can use on an existing function.

The example code is at https://github.com/arjancodes/pycon_nl

Functional programming concerns itself more with the flow of information. It can be more elegant if it fits your problem. Object oriented programming concerns itself more with the structure of the data.

 
vanrees.org logo

Reinout van Rees

My name is Reinout van Rees and I program in Python, I live in the Netherlands, I cycle recumbent bikes and I have a model railway.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):