[Python-Dev] Why does TemporaryDirectory not wait for `__enter__`?

cool-RR cool-rr at cool-rr.com
Sat Feb 26 15:45:48 CET 2011


On Sat, Feb 26, 2011 at 4:39 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Sat, Feb 26, 2011 at 10:52 PM, cool-RR <cool-rr at cool-rr.com> wrote:
> > Hello,
> > I noticed that the `TemporaryDirectory` context manager creates the
> folder
> > on `__init__` rather than on `__enter__`, resulting in complexity, bugs,
> and
> > hackarounds in `__del__`. I assume there's a good reason for this
> decision.
> > What is it?
>
> From the docstring: "This has the same behavior as mkdtemp but can be
> used as a context manager." Like files, it *can* be used as a context
> manager, but doesn't have to be.
>
> Also, the complexity wouldn't go away even if the directory creation
> was delayed until the __enter__ invocation. People can still call
> __enter__ directly, so __del__ would still be obliged to try to clear
> things up as best it could.
>
> Cheers,
> Nick.


I think that if someone calls `__enter__` directly, he takes the
responsibility of calling `__exit__`, so we don't really have to help him
with `__del__`.

But other than that I understand the motivation for making it start on
`__init__` rather then `__enter__`. I'll just make my own version of it that
will work on `__enter__` instead.

Thanks,
Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20110226/aaf0e84a/attachment.html>


More information about the Python-Dev mailing list