[Python-ideas] Automatic context managers
Georg Brandl
g.brandl at gmx.net
Fri Apr 26 19:17:26 CEST 2013
Am 26.04.2013 17:25, schrieb anatoly techtonik:
> Right, there is no proposal, only vague handwaving. I haven't seen anything
> yet that wouldn't require the use of refcounting (the file is closed as soon
> as the last reference to the file object goes away), or some serious magic
> (when you want the file object to be closed even when read raises an exeption).
>
> When you want to propose something you need to do some work yourself. That
> doesn't mean you have to provide a patch, but you do need to specify your
> proposal detailed enough to understand it without trying to second guess you.
>
> The batteries of my crystal ball ran out,
>
>
> Ok. The proposal is patch Python to be able to write:
>
> boolean = open(resource).use()
>
> Instead of:
>
> boolean = None
> with open(resource) as tempvar:
> boolean = tempvar.use()
>
> That's it. I am not pretending I know how to implement it. I just expressed my
> opinion that this might be possible, because PySide seems to do this somehow.
Well, then consider this proposal rejected. It's nothing new, objects have
cleaned up resources in their __del__ (or equivalent C-level
destructor/finalizer) for ages. PySide doesn't do anything different, and
as others have mentioned, due to CPython's use of reference counting you can
get deterministic behavior if you are careful not to create cycles.
However, at least for resources like files this is *exactly* what we have been
moving away from even before the introduction of the "with" statement; in fact,
in today's Python the destructor of file objects emits a ResourceWarning (which
is silent by default, since many users still rely on this behavior; but you
can see it with "python -Wa"). There are several good reasons for this:
* Explicit is better than implicit: letting Python handle resource cleanup is
possible to manage, especially for small numbers of resources and small pieces
of code, it quickly gets annoying and creates exactly the sort of problem that
Python usually does away with: tracking object lifetimes yourself. With a
"with" statement, you know that your resources *are* cleaned up, and when.
* Most other Python implementations have never had reference counting, and never
will (e.g. PyPy). Collecting their unreachable objects differently enables
optimizations.
Georg
More information about the Python-ideas
mailing list