[Python-ideas] Automatic context managers

Cameron Simpson cs at zip.com.au
Thu Apr 25 10:16:40 CEST 2013


On 25/04/13 14:47, anatoly techtonik wrote:
| >On Thu, Apr 25, 2013 at 7:23 AM, Cameron Simpson <cs at zip.com.au> wrote:
| 
| >>Then aren't you just talking about the __del__ method?
| >
| >No. The __del__ method is only called during garbage collection phase which
| >may be delayed. In PySide the QObject is deleted immediately.

The CPython doco says when the reference count goes to zero. (Snippet
below.) So in your example, also immediately.

Garbage collection can find find detached objects whose count hasn't
gone to zero, but I think your example would fit the refs-gone-to-zero,
and anyway I think that was your criterion for having this work in
the first place (automatically).

So I'm not sure how __del__ is particularly less predictable than
your "implicit" scenario.

Then at 25Apr2013 16:17, Steven D'Aprano <steve at pearwood.info> wrote:
| Citation please. Where is this documented?

Well, the 3.2.3 doco on __del__ says:


  Called when the instance is about to be destroyed. [...] It is
  not guaranteed that __del__() methods are called for objects that
  still exist when the interpreter exits. [...]
  del x doesn’t directly call x.__del__() — the former decrements
  the reference count for x by one, and the latter is only called
  when x‘s reference count reaches zero. [ <-- Obviously only valid
  for ref counting Python implementations. - Cameron ] Some common
  situations that may prevent the reference count of an object from
  going to zero include: [...]

The 2.7 doco is very similar.

So, yes, when references go to zero. But as you say later, that may
never happen. The GC _may_ find isolated circles and delete then,
thus at GC time in anatoly's nomenclature.

Reference counting makes __del__ fairly predictable if you have
tight control over the references to an object. Not always the case
of course. And other Pythons don't necessarily do reference counting
unless I misremember.

| Or, and for the record, the reason that with statements work so
| well is because they are guaranteed to be deterministic. You cannot
| leave the with block without the __exit__ method being called. It
| doesn't matter whether you have one reference to the context manager
| object or ten references, the __exit__ method is still called, and
| the object still exists.

This is why I'm for with statements also.

| That is *very* different from a destructor method.
[... snip other stuff I agree with...; I fact I agree with everything
  you say but anatoly is not totally off the mark with "GC time". ]

Yep.
-- 
Cameron Simpson <cs at zip.com.au>

I am now convinced that theoretical physics is actual philosophy.
        - Max Born



More information about the Python-ideas mailing list