[Python-Dev] Object finalization for local (ie function) scopes
Oliver Schoenborn
oliver.schoenborn at utoronto.ca
Sat Jun 12 20:27:49 EDT 2004
This never got sent, sorry, may help...
From: "Martin v. Löwis" <martin at v.loewis.de>
> Oliver Schoenborn wrote:
> >>It doesn't work in Python. I believe your implementation also fails in
> >>Jython (but didn't test).
> >
> >
> > Unless we're talking cross-purpose here, scope.py shows it works at
least in
> > Python downloaded from python.org. Again, could you please be more
specific,
> > pointing to which part of the code is allegedly flawed or not portable?
>
> Try running it with Jython 2.1, available from www.jython.org. I get the
> error
>
> ImportError: no module named inspect
I checked on the jython site, the cvs repository, and the inspect module is
only partially implemented as a wrapper around the Python inspect module.
This problem you are having seems related to implementation, not technique.
The technique itself can be summarized as follows:
- Create a function that wraps a try/finally around the function of interest
- Make class whose instances need "cleanup" automatically tell the function
in which they were created (the "function of interest" above) that they
should be cleaned up upon function exit. This requires three things:
- A new class in which that functionality can be encapsulated so the
user doesn't have to replicate it every time; just need to derive from it
- Someone (the new class, or the wrapper) to create new function
attribute
- When an object is instantiated, add ref to self to the new, special
function attribute, like Python allows. This itself requires:
- Find function in which self was instantiated so that the function
attribute can be accessed
The inspect module is used in the very last task. The new function attribute
is only used as a convenient place to store information which is closely
tied to the function. But there are other possibilities. E.g. instead of
creating a function attribute, the ScopeGuardian could use a global stack of
list of objects. An instance of NeedsFinalization would use the top list of
the stack to add a reference to istelf there.
It looks like Jython has some parts of python lib implemented natively, some
borrowed, and some not implemented, based on need and manpower, so the fact
that the inspect module is not available hardly qualifies the technique as
"not working". If Jython doesn't use stack, and implementing in terms of
global var not feasible, *and* there is no other implementation possible in
Jython, then yeah, I agree, scope.py is not portable to Jython. However that
doesn't mean that the technique can't be implemented different in Python
interpreter and Jython interpreter.
Cheers,
Oliver
More information about the Python-Dev
mailing list