[Python-Dev] Re: closure semantics
eppstein at ics.uci.edu
Wed Oct 22 19:03:06 EDT 2003
In article <18.104.22.168.0.20031022191732.0280ce10 at pop.bluewin.ch>,
Samuele Pedroni <pedronis at bluewin.ch> wrote:
> why exactly do we want write access to outer scopes?
> for completeness, to avoid the overhead of introducing a class here and there,
> to facilitate people using Scheme textbooks with Python?
I am currently working on implementing an algorithm with the following
- It is an algorithm, not a data structure; that is, you run it,
it returns an answer, and it doesn't leave any persistent state
- It is sufficiently complex that I prefer to break it into several
different functions or methods.
- These functions or methods need to share various state variables.
If I implement it as a collection of separate functions, then there's a
lot of unnecessary code complexity involved in passing the state
variables from one function to the next, returning the changes to the
variables, etc. Also, it doesn't present a modular interface to the
rest of the project -- code outside this algorithm is not prevented from
calling the internal subroutines of the algorithm.
If I implement it as a collection of methods of an object, I then have
to include a separate function which creates an instance of the object
and immediately destroys it. This seems clumsy and also doesn't fit
with my intuition about what objects are for (representing persistent
structure). Also, again, modularity is violated -- outside code should
not be making instances of this object or accessing its methods.
What I would like to do is to make an outer function, which sets up the
state variables, defines inner functions, and then calls those
functions. Currently, this sort of works: most of the state variables
consist of mutable objects, so I can mutate them without rebinding them.
But some of the state is immutable (in this case, an int) so I need to
somehow encapsulate it in mutable objects, which is again clumsy.
Write access to outer scopes would let me avoid this encapsulation
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-Dev