I do hope Python keeps incorporating more of the "good stuff" from functional programming. List/dict/set comprehensions make code better - I can look at something and see very clearly that it's correct. Type hinting is a great compromise between beginner/quick scripting needs and offering a fully-baked type system. Type hints do a lot more than most people expect - you can create useful compound and custom types (like Tuple[Int, Str, Iterable]). If we can get some pattern matching in there I'm not sure what I'd do. Spend less time debugging test failures I guess. Not sure what I'd do with that time. Maybe see my family or learn how to bake pastry. Or finally clean the top of the stove. Or just write more Python in the same amount of time? I don't know. Pattern matching.<p>Cool library, though.
This is neat. It reminds me of an silly project [0] I made a while back to implement do-notation in python. In OP's project you still end up with code that's basically this:<p><pre><code> y = (Maybe(just=x) if x > 0 else Maybe()).bind(lambda a:
Maybe(just=x*a) .bind(lambda b:
Maybe.mreturn(a+b)))
</code></pre>
It's functionally sound and standard, but ergonomically painful. I built a really fun horrible hack to allow you to write that instead as this:<p><pre><code> with do(Maybe) as y:
a = Maybe(just=x) if x > 0 else Maybe()
b = Maybe(just=x*a)
mreturn(a+b)
</code></pre>
It swaps out the assignment operator `=` in the `with do()` block for the monadic bind operation, which you might be used to seeing as `<-`.<p>You just need to use my @with_do_notation decorator, which just completely rewrites your function using the ast library wherever it finds a block of `with do(SomeClass) as variable:`. I was even able to write ergonomically nice parser combinators [1] that would actually work pretty well if python had tail call optimization.<p>You shouldn't use it but it was great fun and opened my eyes to the ways you can abuse python if you really wanted to. Using decorators to introspect and completely rewrite functions is a fun exercise.<p>[0] <a href="https://github.com/imh/python_do_notation" rel="nofollow">https://github.com/imh/python_do_notation</a><p>[1] <a href="https://github.com/imh/python_do_notation/blob/master/parser_example.py#L97" rel="nofollow">https://github.com/imh/python_do_notation/blob/master/parser...</a>
I like strongly typed and functional programming. But I would rather use a "pythonic" approach to solve problems in python.
OFC there might be some cases where for example one of your dependency is python, and you still want to be able to write correct code. But in general, If you want types and functional constructs, IMO you should use something else.
If there was one thing I'd change with python to make it more 'functional' it would be having lambdas that weren't expression-only. I know it's not a functional feature because it's for stateful programming, but the lack of it disallows some nice stuff.
Hi, author of `returns` here! Thanks a lot for sharing this link.<p>I would love to highlight several features of `0.14` release we are working on right now:<p>1. Typed `partial` and `curry` functions: <a href="https://returns.readthedocs.io/en/latest/pages/curry.html" rel="nofollow">https://returns.readthedocs.io/en/latest/pages/curry.html</a><p>2. `Future` and `FutureResult` containers for working with async Python! <a href="https://returns.readthedocs.io/en/latest/pages/future.html" rel="nofollow">https://returns.readthedocs.io/en/latest/pages/future.html</a><p>3. Typed functional pipelines with very good type inference: <a href="https://returns.readthedocs.io/en/latest/pages/pipeline.html" rel="nofollow">https://returns.readthedocs.io/en/latest/pages/pipeline.html</a><p>It is going to be released soon, stay tuned!
The project cites this blog post[0] on the "anti-pattern" that is Python exceptions, and I honestly couldn't be turned off on this project anymore after reading it if this is the inspiration behind it.<p>The examples in the README and this blog post just give me huge "nope" vibes. Obviously Python could learn a lot more from functional programming, but this is the wrong way to go about a lot of it.<p>0. <a href="https://sobolevn.me/2019/02/python-exceptions-considered-an-antipattern" rel="nofollow">https://sobolevn.me/2019/02/python-exceptions-considered-an-...</a>
How about writting modern and proper Python first? Not to mention designing a decent API?<p>Let's examine the README example for a minute:<p><pre><code> user: Optional[User]
if user is not None:
balance = user.get_balance()
if balance is not None:
balance_credit = balance.credit_amount()
if balance_credit is not None and balance_credit > 0:
can_buy_stuff = True
else:
can_buy_stuff = False
</code></pre>
I don't know if it's been deliberatly twisted, but that's not what I would called idiomatic or realistic for a Python program:<p>- one should probably never reach this part of the code if there is no user. But I'll indulge the author.<p>- don't put can_buy_stuff in an else close, what's the point?<p>- using type hints for no reason, but not other modern facilities like the walrus operator?<p>- do we really want users without a balance? Let's indulge this, but it seems a bad design.<p>- what's with all those unecessary conditional blocks?<p>- credit_amount should never be None. It's a Balance object, put a sane default value. But ok, indulging again.<p>So, you get down to:<p><pre><code> user: Optional[User]
can_buy_stuff = False
if user and (balance := user.get_balance()):
can_buy_stuff = (balance.credit_amount() or 0) > 0
</code></pre>
I don't think the solution the lib offers is superior:<p><pre><code> can_buy_stuff: Maybe[bool] = Maybe.from_value(user).map(
lambda real_user: real_user.get_balance(),
).map(
lambda balance: balance.credit_amount(),
).map(
lambda balance_credit: balance_credit > 0,
)
</code></pre>
And that's if we are using the rules of the README, which are not fair.<p>If we have a well designed API, and we use a function (more testable, and hey, are we doing FP or not ?), then:<p><pre><code> def can_buy_stuff(user: User):
if (balance := user.get_balance()):
return balance.credit_amount() > 0
return False
</code></pre>
Checking the user should not be part of this algo, credit_amount should be 0 if never set. We could even remove return False, I keep it because I like explicitness.<p>You could even that as a method or raise NoBalance depending of your case.<p>Bottom line, if you really feel that strongly about None, don't jump on the bazooka to kill this fly, go to <a href="https://discuss.python.org" rel="nofollow">https://discuss.python.org</a> and advocate for PEP 505 (None-aware operators): <a href="https://www.python.org/dev/peps/pep-0505/" rel="nofollow">https://www.python.org/dev/peps/pep-0505/</a><p>It's been deferred since 2015.<p>That doesn't mean we should not experiment with other paradigms in Python, and I do think this lib is an interesting experiment, but I don't find it conclusive.
For 'Maybe' an 'Result' specifically, I feel that Python builtins + mypy offer superior experience: easier, safer, and less dependencies with a similar level of verbosity.<p>For Maybe example: I think this 'functional' style with fmaps in Python is problematic, because lambdas can't be multiline. If you have sevearal lines of logic, you'd need an auxiliary helper def, and at this point it becomes as unreadable.<p>For Results: I think returning Union[Exception, Value] (where Value is the 'desired' type) and then using isinstance(result, Exception) is much cleaner.<p>- it can be statically checked with mypy to ensure the same level of type safety as Rust would have<p>- minimal performance impact<p>- no extra wrapping and unwrapping in the code. You can completely ignore mypy and error handling, until you're happy, then you harden your program by making sure it complies to mypy.<p>- no extra dependencies, third party code dealing with your library doesn't have to deal with your wrappers! If they don't check for error type, when Exception is encountered, the program will most likely terminate with AttributeError, which is a desirable behaviour in such situation.<p>- it's much easier to compose: propagating error with a decorator is neat, until you have some more sophisticated logic, e.g. for error aggregation<p>- the only downside is that you end up with occasional `if isinstance(result, Exception)...`.<p>I reviewed results library specifically here [0] and elaborate on different error handling techniques in Python, including the approach I described.<p>[0] <a href="https://beepb00p.xyz/mypy-error-handling.html#container" rel="nofollow">https://beepb00p.xyz/mypy-error-handling.html#container</a>
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.<p>And that’s how your initial refactored code will look like:<p><pre><code> 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,
)
</code></pre>
Much better, isn’t it?
Why the lambdas at all in these examples...<p><pre><code> (lambda real_user: real_user.get_balance())
</code></pre>
and not<p><pre><code> User.get_balance
</code></pre>
(besides subclasses not getting their balance called...)
Functional programming in Python:<p>Step 1: try to integrate more functional methods in your current Python programming due to their usefulness.<p>Step 2: get increasingly frustrated, and then give up, because Guido and the Python devs seemingly hate functional programming and keep hobbling it.
The `Maybe` container seems to be a close analog of `Option` in Rust<p><a href="https://doc.rust-lang.org/rust-by-example/std/option.html" rel="nofollow">https://doc.rust-lang.org/rust-by-example/std/option.html</a>
Python is all about the magic. Lambda expressions are a bit of a black box for me in Python, it would be nice if that was made more transparent, or perhaps a different function entirely
can't say i'm a fan of the decorator to implement functional concepts. jut feels dirty. type hints in python are just as meh. feels like it's not taking advantage of pythons duck typing.<p>a version of try and either, with a decent do notation taking advantage of for comprehension...
<a href="https://github.com/papaver/pyfnz" rel="nofollow">https://github.com/papaver/pyfnz</a>
> But, having null checks here and there makes your code unreadable.<p><pre><code> if user is not None:
balance = user.get_balance()
if balance is not None:
balance_credit = balance.credit_amount()
if balance_credit is not None and balance_credit > 0:
can_buy_stuff = True
else:
can_buy_stuff = False
</code></pre>
Actually I think that's very readable<p><pre><code> 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?
</code></pre>
No?!? That's much worse.
Nice premise. But it makes the Python code look super complicated.<p>It overloads map() with a lambda function, to compose function pipelining.<p>Then, it introduces flow() as the new pipelining tool. But you have to use bind() on the last function call to return the value.<p>Interesting concepts, but unless Python incorporates this as a standard feature, then this will remain a fringe idea. And it will add significant load to the development and maintenance process of Python programs.<p>Admittedly, I like Elixir’s pipe forward concept |><p>That makes it super simple to do functional composition, and it will automatically bind and return the last value.<p>Then getting the user profile, can be like so:<p><pre><code> user_profile =
userid |> get_request |> parse_json</code></pre>