del

Andrew Dalke adalke at mindspring.com
Fri Feb 14 20:57:16 EST 2003


Daniel Silva:
>  More precisely, how many programs would be broken if a python
> compiler did not implement it?

One of my libraries would break.  I have a C library in which
certain objects (referenced through integer handles) must be
deallocated by users of the library.  I have a wrapper object
which looks like this

class smart_ptr:
    def __init__(self, handle):
        self.handle = handle
    def __del__(self):
        if not dt_dealloc(self.handle):
            raise AssertionError("incorrect deallocation order!")

This lets me hook into Python's garbage collection mechanism.

Some of the data types have internal dependencies on others,
so that children are deallocated before parents.  For example,

class SmartsPattern:
    def __init__(self, handle):
        self.handle = handle
    def match(self, molecule):
        ...
        match_obj = smart_ptr(dt_smarts_match(self.handle, molecule))
        return SmartsMatch(self.handle, match_obj)

class SmartsMatch:
    def __init__(self, pattern_handle, match_handle):
        self.pattern_handle = pattern_handle
        self.match_handle = match_handle

def search():
    from daylight import Smiles, Smarts
    molecule = Smiles.smilin("c1ccccc1")
    pattern = Smarts.compile("[#6]")
    return pattern.match(molecule)

def main():
    match = search()

When main() is called, match exists and is a SmartsMatch
instance, with a reference to both the pattern_handle and
the match_handle.  No one else has a reference to either handle.

When 'match' goes out of scope, its instance variables
are removed, and each handle's count goes to 0, triggering
the call to dt_dealloc.

The C-level toolkit manages some object dependencies.
When a pattern object is deleted in the underlying library,
all of its children (the match objects) are also removed.
So if the Python library deallocates the pattern object first,
then it must not delete the match objects.

In other words, the order of deletions is important - Python
should delete the match object first and then the pattern
object, which means I need to help it out with a special
purpose deallocator

class SmartsMatch:
    ....
    def __del__(self):
        del self.match_handle
        del self.pattern_handle


                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list