Idioms in python: closure vs functor vs object

So the correct answer to this is the callable object, which essentially replaces the idiom of the closure in python.

so working off option 3 above change:

class Calculator(Object) :
    def __init__(self):
        self.previous_state=None

    def do_something(self, current_state) :
        #do_something
        self.previous_state = current_state
        return something

to

class Calculator(Object) :
    def __init__(self):
        self.previous_state=None

    def __call__(self, current_state) :
        #do_something
        self.previous_state = current_state
        return something

and now you can call it like a function. So

func = Calculator():
for x in list:
    func(x)

You can define a generator, which is a restricted form of a coprocess.

def make_gen():
    previous_state = None
    for row in rows:
        # do something
        previous_state = current_state
        yield something

thing = make_gen()
for item in thing:
    # Each iteration, item is a different value
    # "returned" by the yield statement in the generator

Instead of calling thing (which replaces your inner function) repeatedly, you iterate over it (which is basically the same as calling next(thing) repeatedly).

The state is entirely contained within the body of the generator.

If you don't want to actually iterate over it, you can still selectively "re-enter" the coprocess by calling next explicitly.

thing = make_gen()
first_item = next(thing)
# do some stuff
second_item = next(thing)
# do more stuff
third_item = next(thing)
fourth_item = next(thing)
# etc

Tags:

Python