r/Python • • May 30 '25

Resource Functional programming concepts that actually work in Python

Been incorporating more functional programming ideas into my Python/R workflow lately - immutability, composition, higher-order functions. Makes debugging way easier when data doesn't change unexpectedly.

Wrote about some practical FP concepts that work well even in non-functional languages: https://borkar.substack.com/p/why-care-about-functional-programming?r=2qg9ny&utm_medium=reddit

Anyone else finding FP useful for data work?

137 Upvotes

41 comments sorted by

View all comments

Show parent comment

3

u/eras May 31 '25 edited May 31 '25

Allows accidental field access, leading to runtime errors.

In Python almost all you have is runtime errors, yes, but with mypy and this function (pyright notices the same, but Typed Python (or "Tython") is of course a subset of real Python..):

def area2(shape: Shape) -> float:
    return 3.14 * shape.r ** 2

you do actually get the error

foo.py:33: error: Item "Point" of "Union[Point, Circle, Rectangle]" has no attribute "r"  [union-attr]
foo.py:33: error: Item "Rectangle" of "Union[Point, Circle, Rectangle]" has no attribute "r"  [union-attr]

But there's no way to get non-exhaustive match warnings. Though perhaps static type checkers could flag the cases where you reach the assert False statement.

Additionally there's this nicer way of writing the function since Python 3.10:

def area3(shape: Shape) -> float:
    match shape:
        case Circle(r=r):
            return 3.14 * r**2
        case Rectangle(w=w, h=h):
            return w * h
        case Point():
            return 0

Btw, if you just write Circle(r) there, r gets value 0 :-). Nice trap.

But yeah, the Union type is not quite the match for functional language sum types. This difference can be easily seen with OCaml:

(* type 'a option = Some of 'a | None (* this is in standard library *) *)

let rec find_value f list =
  match list with
   | x::_ when f x -> Some x
   | _::rest -> find_value f rest
   | [] -> None (* compiler would warn about this case missing *)

let value = find_value (fun x -> x = None) [Some 5; Some 3; None]

value is now Some None, something Python isn't very willing to represent via its Union type, you need intermediate classes to do it.