In python, can I create a closure with an anonymous function?

50 Views Asked by At

Out of curiosity, I'd like to see if there's a better answer than what's below. How can I convert this:

def counter():
    ctr = 0
    def inner():
        ctr += 1
        return ctr
    return inner
counter = counter()

into this javascript equivalent?

counter = (function() {
    let ctr = 0;
    return function() {
        return ++ctr;
    } //inner anonymous func
})(); //outer func, called and forgotten, sort of.

The python above is fine, I was just curious if there was a faster/more readable way to do this.

To be clear, I don't want the outer factory function to be available after its called, and I want it to be called as soon as its defined. Think of it as a closure singleton. Thanks!

0

There are 0 best solutions below