Re:Show HN: Koda, a typesafe functional toolkit for Python
by FreakLegion on Tuesday February 08, 2022 @03:56AM
(#30256232)
Especially given the first example is tailor-made for the walrus operator.
if (balance := user.get_balance()) and (credit := balance.credit_amount()):
discount_program = choose_discount(credit)
(Omitting the credit > 0, and without getting into other fundamental issues with the implied design, since it's just a readme example.)
Re:Show HN: Koda, a typesafe functional toolkit for Python
by properdine on Tuesday February 08, 2022 @01:19AM
(#30255459)
I agree with you that the second is less readable and less pythonic (feels more JS/Node-ish).
Re:Show HN: Koda, a typesafe functional toolkit for Python
by chrischen on Wednesday February 09, 2022 @03:13PM
(#30277817)
The second example is a pretty standard monadic composition pipeline. In languages like Haskell or F# there can be special syntax to make it easier to read (do notation or computation expressions).
However if you’ve never done it will be hard to read. It’s easy to read to someone who has the background, and it is easier to refactor and less error prone because the context of a nullable value (the if statement checks) is factored out from the core logic. So if the core logic needs to be changed it can be done so without touching the if statement checking for None.
1
===================
user: Optional[User]
discount_program: Optional['DiscountProgram'] = None
if user is not None:
2===================
user: Optional[User]
discount_program: Maybe['DiscountProgram'] = Maybe.from_optional(
).bind_optional( # This won't be called if `user is None` ).bind_optional( # This won't be called if `real_user.get_balance()` is None ).bind_optional( # And so on!