"Gregory Petrosyan" <[EMAIL PROTECTED]> writes: > I'm not very familiar with Python, so please explain me why should > containers be used? > For example in one of Paul Graham's essays there's an example of > 'generator of accumulators' in Python: > > def foo(n): > s = [n] > def bar(i): > s[0] += i > return s[0] > return bar > > 1) So, why just using 's = n' is not suitable? (It doesn't work, Python > 'doesn't see' s, but why?)
The Python assignment statements bind a name to a value. By default, they bind it in the current namespace. Doing "s = n" (or s <op>= n) in the function bar binds the name s in the function bar, and leaves the value in foo as it was. "s[0] = i" (or s[0 += i) binds the name s[0], not the name s, and hence mutates the object bound to s instead of binding s in the function bar's namespace. In reality, this is implemented by a mutator method of s, but it *looks* like you're binding s[0]. > 2) Is 'foo.s = n' a correct solution? It seems to be a little more > elegant. (I tested it, and it worked well) It's basically the same solution. You're replacing binding a variable with mutating an object bound to a name in an outer scope. In one case the container is named s and is a list that you're setting an element of. In the other case, the container is named foo and is an object that you're setting an attribute on. <miker -- Mike Meyer <[EMAIL PROTECTED]> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list