3 ms·
Which popular language nowadays doesn't have closures? Even the so hated (by HN) PHP has had that for many years already.
by jafaku 12y ago
Which popular language nowadays doesn't have closures? Even the so hated (by HN) PHP has had that for many years already.
- tomjen3 12y agoPython is often claimed not to have closures but that isn't really true, what it doesn't have is anonymous functions. It does have a lambda statement, but that is limited to a single statement. So what you end up writing is more akin to: def multiplier_maker(a): def temp(b): return b * a return temp That is because Python allows you to declare a function anyware, even inside other functions.
- sebleblanc 12y agoAnd if you want to emulate static variables in a function, you can do that: def counter(): counter.x += 1 return counter.x counter.x = 0 counter() > 1 counter() > 2 Beware! singleton variables, mutable state, etc.
- knome 12y agoYou can do it by closing over a variable as well. Python closes over things just fine, it just has problems rebinding variables in outer scopes that aren't the global one. Here, I just make the variable a container, so I can alter a value inside it, instead of rebinding it ( only python2 has this problem, python3 has a "nonlocal" keyword to work around this in the language ) >>> def counter(): ... x = [ 1 ] ... def count(): ... y = x[ 0 ] ... x[ 0 ] += 1 ... return y ... return count ... >>> count = counter() >>> count() 1 >>> count() 2 >>> count() 3 >>> count() 4 >>> >>> otherCount = counter() >>> otherCount() 1 >>> otherCount() 2 >>> count() 5 >>> count() 6 >>> otherCount() 3 >>>
- jafaku 12y ago> what it doesn't have is anonymous functions If it's not anonymous it's not a closure though.
- tomjen3 12y agoBullshit. It closures around its environment, it is a closure.
- nemothekid 12y agoPython.
- knome 12y agoUnder what definition of closure does python lack them?