Ulrich Eckhardt wrote:
Hi!

I'm currently converting my bioware to handle Python code and I have
stumbled across a problem...

Simple scenario: I have a handle to a resource. This handle allows me to
manipulate the resource in various ways and it also represents ownership.
Now, when I put this into a class, instances to that class can be shared,
using Python's reference counting. What I'm missing is a way to
automatically release the resource, something which I would do in the
destructor in C++.

Any ideas how to solve this?

Uli

As someone else pointed out, 'with' is the first line of defense. It makes the stuff you could already do with try/except/finally much easier to get right.

Look also at 'del' a command in the language which explicitly deletes an object.

But I'm guessing you want something that automatically deletes objects whenever the last reference disappears. That's an implementation detail, not a language guarantee. In particular CPython does what you want, by using reference counting. That's the only Python I've used, so it's only hearsay when I say that other implementations, (maybe Cython or Jython) do not all work the same way.

In CPython, any object whose *last* reference goes away, will get immediately deleted. So if you avoid circular references, it should do just what you want. Orphaned circular references are caught by the garbage collector, which runs periodically, but is non-deterministic.

Two more caveats. Exceptions tend to hang onto stuff in their near vicinity, and I can't tell you the algorithm for what happens. But an explicit del in the except clause can probably handle that.

Finally, closures can hang onto stuff. So if you have nested functions, or lambda functions, it's possible they're going to keep things longer than you realize.



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to