3 ms·
The original post is from 2003. Much has changed since then. For example, in Python 3.x it's possible to write the "counter" example like this: def make_coun
by zephyrfalcon 16y ago
The original post is from 2003. Much has changed since then. For example, in Python 3.x it's possible to write the "counter" example like this:
def make_counter():
count = 0
def f():
nonlocal count
count = count + 1
return count
return f
c = make_counter()
for i in range(3):
print(c())
(In Python 2.x and earlier, you would probably create a Counter class to do the same thing. That approach was, and likely still is, considered more "Pythonic", by the way.)
- lispm 16y agoI understand that. Still he said 'Python has closures' in the title and failed to give examples of closures.
- btilly 16y agoNo, he gave examples of things that really are closures, but failed to test them in ways that would have demonstrated that they in fact are closures.
- lispm 16y agoNo, closures are created when functions are passed or returned and there are free variables used in such a function. He did neither pass a function nor return one. The function itself is not a closure. The closure is an object that bundles a function and an actual set of bindings.
- omaranto 16y agoIn some languages, when you neither pass nor return a function a closure is not created. You can regard this as an optimization; in Python the closure is always created as far as I understand.
- lispm 16y agoThat looks more like a choice of some implementation and hopefully not of the language. I would hope for 'Python' that a Python compiler doesn't do that. There is no need to create a closure, when it is never needed. Requiring that for each call of a function with some local functions, closures are created for those, has little to do with 'we have closures', but more with a silly implementation.
- omaranto 16y agoI don't know if any python implementations avoid creating unnecessary closures, but you are right that I meant a specific implementation: CPython. I am not too familiar with python in the present and maybe the following has changed: there isn't really a definition of the language, but the documentation (which was written for the main implementation, but is the closest thing to a definition of the language) does mention that declaring a function creates a function object (closure) and assigns it to a local variable. Of course, an implementation should probably feel free to contradict the documentation when the difference is not observable.