does python have useless destructors?
Tim Bradshaw
tfb+google at tfeb.org
Fri Jun 11 09:24:19 EDT 2004
dkturner at telkomsa.net (David Turner) wrote in message news:<e251b7ba.0406100011.39a795e1 at posting.google.com>...
>
> This makes me sad. But there is some hope in the following pattern,
> although it can be quite awkward:
>
> def with_file(fname, mode, oper):
> f = open(fname, mode);
> try:
> oper()
> finally:
> f.close()
>
> Of course, this can very quickly turn your code into so much
> functional goo. That's not necessarily a bad thing, as Lisp
> programmers can attest... But it's still not quite as powerful as
> RAII.
No Lisp programmer worth their salt would tolerate such a horror. In
the specific case above there's already an idiom for doing this in
Common Lisp:
(with-open-file (s fname ...)
...)
In the general case of cleanup actions, a decent Lisp programmer would
rapidly create their own idiom (arguably CL should provide a
higher-level cleanup framework as implementing the idiom correctly is
not completely simple). Mine is called LET/FINALIZING:
(let/finalizing ((s (open fname ...)))
...)
Is the same as the above WITH-OPEN-FILE incantation, but can be
generalised to any object which may need finalizing. You simply need
to tell the system how to finalize the object, either by defining a
suitable method on a generic function, or even at the site of use if
you only plan on doing it in one place:
(let/finalizing ((s (make-lock ...)
;; Call-specific finalizer
#'(lambda (l abortp)
(when abortp (warn "Whoops"))
;; and punt to the global one
(finalize-thing l abortp))))
...)
--tim
More information about the Python-list
mailing list