
Cover image credit: this amazing StackOverflow answer.
I've learned about closures a few different times, and each time, I've come away feeling li...
For further actions, you may consider blocking this person and/or reporting abuse
There's no reason why global functions with global variables can't be considered closures as well. They wrap up their state in the function. This is particularly true when exporting functions from modules.
In Leaf I consider closures and instance functions to be basically the same. A closure is merely a class instance with an implicit
this
. Under the hood there's not much difference at all.Interesting. I never thought about it like that before. That’s some great under-the-hood knowledge to have. Although instantiating a closure’s state by importing a module (if that state is intended to be mutable) makes my programmy danger sense tingle a little bit.
I love closures and find myself reaching for them often. The only time I've noticed that they don't work for me is when I'm multiprocessing as they won't pickle. In those situations, I have to fall back to the class approach. Maybe I just haven't found the right magic to make them work in process pools, so hopefully someone can point me in the right direction.
If you like closures, try one of the more functional oriented languages (or techniques, since Python also support functions as first class objects). It takes to the next level of thinking and help you write even more concise/elegant code.
Check out the Toolz library for functional techniques written in Python. My favorites are pipe, curry, and compose.
toolz.readthedocs.io/en/latest/api...
It also has the same API implemented in C in the CyToolz library.
I think there is a typo in the first example, it build_zoo should return add_animal. Thanks for writing this article it was a good read!
Thanks! I had somebody on Twitter point that out too. I’ll fix it now.