does python have useless destructors?

Aahz aahz at pythoncraft.com
Thu Jun 17 20:01:32 EDT 2004


In article <e251b7ba.0406150035.16336fb3 at posting.google.com>,
David Turner <dkturner at telkomsa.net> wrote:
>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.

Not really.  Problem is that there's nothing to prevent people from
passing File.fh outside the loop -- and that's standard Python coding
technique!  For that matter, there's nothing preventing a File()
instance from being passed around.  The fact that you've created an
idiom that you want to behave like a similar C idiom has nothing to do
with the way Python actually works.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith, c.l.py



More information about the Python-list mailing list