DEV Community

Cover image for Closure? I Hardly Know Her!

Closure? I Hardly Know Her!

Ryan Palo on February 10, 2018

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...
Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

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.

Collapse
 
rpalo profile image
Ryan Palo

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.

Collapse
 
rwhitt2049 profile image
Ry Whittington

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.

Collapse
 
xngwng profile image
Xing Wang

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.

Collapse
 
rwhitt2049 profile image
Ry Whittington

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.

Collapse
 
nixlend profile image
Nicholas Lee

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!

Collapse
 
rpalo profile image
Ryan Palo

Thanks! I had somebody on Twitter point that out too. I’ll fix it now.