[Python-ideas] Generator-based context managers can't skip __exit__
Ethan Furman
ethan at stoneleaf.us
Fri Nov 18 15:52:31 EST 2016
On 11/18/2016 12:42 PM, Ram Rachum wrote:
> Sure, here are a couple of use cases:
>
> 1. I'm making a program that lets people lease machines. They can issue
> a command to lease 7 machines. When they do, my program leases them one
> by one and adds them all to an exit stack, so in case there aren't 7
> machines available, all the machines we leased get released and the
> situation is back to normal. If everything goes fine, I do pop_all on
> the exit stack so it doesn't get exited and the machines stay leased,
> then the command exits and the user gets his machines.
So you're using the contextlib.ExitStack context manager?
> 2. I have a test suite that creates a temporary folder to put files that
> are used by the test. The temporary folder is created by a context
> manager that deletes it at the end. But, if the test fails I want to
> move the temporary folder away into a dedicated folder for the user to
> be able to examine those files later to figure out why the test fails.
> So I want to tell the temporary folder context manager to not delete
> the folder, because it'll fail since it was moved away so it's not at
> the expected location.
My first thought is to make a custom context manager for this use-case, but if you really want to use a generator instead can't you just put in an existence check for the directory and only delete if it is still there?
--
~Ethan~
More information about the Python-ideas
mailing list