Functional Programming in Python
I’m spending time trying to understand the differences between writing classes and functions in Python. Which one is better and why? From what I’m gathering, a lot of people are tired of writing classes in general. Classes are used in Object Oriented Programming (OOP) and some python coders hate it because it’s writing too many lines of code when only a few really matter. So programmers like functional programming (FP) in python instead.
To that end, I’ve been watching videos of both. OOP and FP videos on the Internet and started writing notes on them. Below is a great but also very deep video on functional
Functional Programming in Python
My notes from the above video are above are below:
- First Class Functions
- Higher Order Functions
- Purity
Immutability(not going to talk about it)- Composition
- Partial Application & Currying
- Purity, a function without ‘side effects’
- First Class Functions, simply means that functions are like everybody else
- Can define with ‘def’ or lambda
- Can use the name of functions as variables and do higher-order programming
- Decorators “… provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.”
- Partial function applications - “The primary tool supplied by the Functools module is the class partial, which can be used to “wrap” a callable object with default arguments. Partial objects are similar to function objects with slight differences. Partial function application makes it easier to write and maintain the code.”
- Partial functions are very powerful
- “Currying transforms a function that takes multiple arguments in such a way that it can be called as a chain of functions. Each with a single argument (Partial Application).” via Wikipedia
- The important concept for Currying is closures, aka lexical scoping
- Remembers the variables in the scope where it was defined
- List comprehensions vs functional equivalents
- Map function vs list comprehension
- Filter function vs list comprehension
- Reduce vs list comprehension
- Why not write out the loop instead? Using Map/Filter/Reduce is cleaner
- Function composition: i.e. run a filter and then map: map(f, filter(p, seq))
- ‘Import functools’ is very useful
- Main takeaways: Function Programming is possible in Python (to a degree)
- Main takeaways: Small composable function are good
- Main takeaways: FP == Build General Tools and Compose them
- Python is missing: more list functions
- Python is missing: Nicer lambda syntax
- Python is missing: Automatic currying, composition syntax
- Python is missing: ADTS (Sum Types)
- Python is missing: Pattern Matching
- Some remedies for list functions
- Links provide in video @ 26:00
- Suggest learning Haskell as a gateway to functional programming.