Talk:Closure (computer programming): Difference between revisions

Content deleted Content added
Demerphq (talk | contribs)
Pgroce (talk | contribs)
Line 87:
 
::I have changed my view on this. Python closures are ''not'' used for the same purposes as Scheme closures. I am told that in Scheme, closures are very commonly used to hide state. In Python, you would just use a class instead. [[User:Jorend|Jorend]] 21:50, 15 February 2006 (UTC)
 
FWIW, Python does allow you to ''modify'' variables in outer scopes; it does not, however, have syntax for ''rebinding'' names in outer scopes to new values. The workaround when this is needed (which isn't often) is to use a mutable container object in the enclosing scope, and replace the contained value rather than the container
 
<pre>
>>> def foo(start=0):
... counter = [start] # counter is 1-element array
... def bar():
... counter[0] = counter[0] + 1
... return counter[0]
... return bar
...
>>> count = foo(10)
>>> print count()
11
>>> print count()
12
>>> print count()
13
</pre>
 
Although Jorend is right that classes are preferred for encapsulation in Python, closures actually hide state better than classes do. All class data is, ultimately, accessible from within Python. I don't think I can get to the counter in the example above without writing a C extension.
 
This is discussed in slightly more depth in [[Talk:Python_programming_language#Closures]]. I like my example better, though. :)
 
This is largely an academic discussion; I'm not suggesting changes to the article. If Python's identity as a language supporting closures does come into question, however, maybe this will head it off. --[[User:Pgroce|Pgroce]] 14:26, 18 May 2006 (UTC)
 
== Removed "merge this with Function object" note ==