does python have useless destructors?

David Turner dkturner at telkomsa.net
Tue Jun 15 04:35:10 EDT 2004


aahz at pythoncraft.com (Aahz) wrote in message news:<cal53o$c1b$1 at panix3.panix.com>...
> In article <e251b7ba.0406132335.6e65beba at posting.google.com>,
> David Turner <dkturner at telkomsa.net> wrote:
> >
> >In fact, the RAII idiom is quite commonly used with heap-allocated
> >objects.  All that is required is a clear trail of ownership, which is
> >generally not that difficult to achieve.  
> 
> Not really.  What you're doing is what I'd call "virtual stack" by
> virtue of the fact that the heap objects are being managed by stack
> objects.
> 

Having read this through a second time, I'm not sure that you
understood the C++ code I posted.  So here is an equivalent in Python:

class File:
    def __init__(self, name):
        self.fh = open(name, "r")
    def __del__(self):
        self.fh.close()

file_list = []
file_list.append(File(file_to_compile))
while len(file_list):
    f = file_list[len(file_list)-1]
    t = Token(f)
    if t == Token.EOF:
        file_list.pop()
    else:
        parse(t)


No stack objects in sight, yet this code is semantically equivalent to
the C++ code.

Don't let red herrings like std::stack confuse you :-).

Regards
David Turner



More information about the Python-list mailing list