Abstracting try..finally with generators (instead of macros)

Beni Cherniavsky cben at techunix.technion.ac.il
Mon Dec 16 06:50:02 EST 2002


On 2002-12-15, Andrew Dalke wrote:

> Beni Cherniavsky wrote:
>
> > About the `sys` reference: I think that the class, being defined in the
> > module (and referncing global variables) retains the module -- which in
> > turn retains sys by having it imported -- so there shouldn't be a problem.
> > Do I miss anything?
>
> I .. don't think it keeps a reference to the module, only the name of
> the module.Else in the pre-garbage collection days there would be
> a lot of cycles.(I think?)
>[snip]
> The problem is that objects in each module need to be deallocated
> during shutdown.How's that done?
>
> I dug up Guido's essay on this from the 1.5 days
>  http://www.python.org/doc/essays/cleanup.html
> Don't know how true it is now.
>
The key that explains it all is:

While modules are generally not involved in cycles (except when there are
mutually recursive imports), a module's dictionary generally is involved
in a cycle because every function and method defined in the module
references its __dict__, and these functions and methods are generally
reachable from that __dict__. Thus, when a module is deleted, I explicitly
clear its __dict__ carefully. (This has always been done, just not
"carefully".)

> So there's no need to worry - 'sys' isn't cleared until the
> very end.
>
`sys.stdout` served just as an example in my code.  Besides, as said
above, you never should worry in Python about functions becoming orphans -
the module's __dict__ can't get deleted as long as the function lives.

-- 
Beni Cherniavsky <cben at tx.technion.ac.il>





More information about the Python-list mailing list