Re:Python-patterns – A collection of design patterns/idioms ...
by kortex on Wednesday June 01, 2022 @04:34PM
(#31587702)
The dry-python lambda soup is awful, I totally agree there. That's just there mostly for demonstration purposes though. Generally you'd actually use the flow construct (monads) to compose methods.
But `obj and obj.method()` really is not the same thing as `obj.map(method)`. "virtual Maybe container/box" is a nice idea, and does actually type-check with mypy (mostly), but you cannot actually compose it with other functions. The problem is, each time you do `obj and obj.method()`, you end up union-ing type(obj) and type(obj.method).
https://mypy-play.net/?gist=5b03d81a64453997984e448df9b889e7
main.py:40: note: Revealed type is "Union[__main__.User, None]"
main.py:41: note: Revealed type is "Union[__main__.User, None, builtins.float]"
main.py:42: note: Revealed type is "Union[__main__.User, None, builtins.float]"
main.py:43: note: Revealed type is "Union[__main__.User, None, builtins.float, builtins.str]"
True Maybe types are more precise. Maybe if the Mypy engine could be retooled to recognise the `obj and obj.method()` idiom as tantamount to `obj.map(method)`, this could be avoided.
Background: an object that either None or true in a boolean context (true unless overriden for custom objects). Given such object, we can consider it in a virtual Maybe container/box. When we want to use it, we have to unwrap it using `obj and obj.method()` syntax. Then `obj.method()` is ordinary "unwrapped" call.
Just to remind you. Here's how "ergonomic" Maybe variant from the article look like:
https://github.com/dry-python/returns#maybe-containerYou can decide for yourself what is more readable: all these lambdas or the `None and f()` code.