Skip to content

Comment on Functional Programming in Python

Comments

I'm a big fan of functional programming but this documentation is kind of funny, unintentionally. I realize there is no better way to do it in Python.

And that’s how your initial refactored code will look like:

  user: Optional[User]

  can_buy_stuff: Maybe[bool] = Maybe.from_value(user).map(  # type hint is not required
      lambda real_user: real_user.get_balance(),
  ).map(
      lambda balance: balance.credit_amount(),
  ).map(
      lambda balance_credit: balance_credit > 0,
  )
Much better, isn’t it?

I'm also a FP fanboy, and this concept doesn't quite convince me. I'm not sure a Maybe type really helps that much in a dynamically typed language. All the safety you get from using Maybes is worth Nothing (pun intended) when credit_amount could still return let's say Just a string, or raises an exception.

If this chain of calls supposedly handles Nones at any level, then .map is not the right method. It should be .flatMap (or .bind). Unless this is a magic .map that handles either X or Maybe[X] and even exceptions (just like JS promises). This flexibility may be convenient and I can appreciate its pythonicness, but it's not really in the spirit of typed FP.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.