1

Is either of the two styles preferred or more "pythonic" for creating closures (edit: "closure-like objects")?

def make_doer(closed_var):
    def doer(foo):
        pass  # Do something with closed_var and foo

    return doer
class Doer:
    def __init__(self, closed_var):
        self._closed_var = closed_var

    def __call__(self, foo):
        pass  # Do something with self._closed_var and foo

The only differences I can tell are that the former is a tiny bit shorter but the second has an advantage in that the docstring for the resulting function (__call__ in the second case) is less nested/hidden. Neither seems like a huge deal, anything else that would tip the balance?

Luis
  • 1,210
  • 2
  • 11
  • 24
  • The second isn't a closure. It is a class with state. [It is a poor man's closure](https://stackoverflow.com/questions/2497801/closures-are-poor-mans-objects-and-vice-versa-what-does-this-mean). In Python, we are rich and have both. Being a bit more serious, you are creating two different things. In the first, `make_doer` returns *a function object*, in the second, `Doer` returns *a `Doer` object*. – juanpa.arrivillaga Jun 19 '20 at 22:48
  • You are correct @juanpa.arrivillaga, updated to say "closure-like" :) – Luis Jun 20 '20 at 02:11

1 Answers1

0

Closures have to do with maintaining references to objects from scopes that have passed, or from earlier scopes.

Here is the simplest example of the form a Closure takes:

def outer(): 
    x=7

    def inner(y):
        return x + y

    return inner

i = outer()
FisheyJay
  • 442
  • 4
  • 10