[Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem
eryksun
eryksun at gmail.com
Sat Jun 22 17:38:23 CEST 2013
On Sat, Jun 22, 2013 at 7:10 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> The function attribute "__closure__" is set to None for regular functions.
> For closures, it is set to a bunch of stuff needed for the inner function to
> work correctly. (No user serviceable parts inside.) Basically, the inner
> function needs to carry around with it a little piece of its environment, so
> it can retrieve the value of "arg" when required.
Using a tuple of cells (loaded from __closure__) allows for fast
lookups. If you check with dis, you'll see the ops used with cells are
LOAD_DEREF and STORE_DEREF. These handle the indirection through the
cell object, which is a flat cost. It's not a function of nesting
level. Using cells also avoids referencing the outer frame(s), which
would interfere with garbage collection (GC).
One catch with Python nested scopes is that binding a name defaults to
the local scope. You can get around this by using a mutable container,
just as was done with globals before the "global" keyword was added in
version 0.9.4 (1991). The better solution is a new keyword, but adding
keywords is radical surgery. The "nonlocal" keyword, as Peter used,
had to wait for 3.x.
More information about the Tutor
mailing list