[Python-ideas] Generator-based context managers can't skip __exit__

Greg Ewing greg.ewing at canterbury.ac.nz
Fri Nov 18 16:00:10 EST 2016


Ram Rachum wrote:
> 1. I'm making a program that lets people lease machines. They can issue 
> a command to lease 7 machines. ... If everything goes fine, I do pop_all on
> the exit stack so it doesn't get exited and the machines stay leased, 

Seems to me that would be done more easily and clearly
without involving a context manager at all:

    machines = []
    try:
       for i in range(num_machines_required):
          machines.append(lease_machine())
    except AllMachinesInUseError:
       for machine in machines:
          release_machine(machine)
       del machines[:]

A context manager is a tool to be used if it helps. If it
doesn't help, don't be afraid to not use it!

> 2. I have a test suite that creates a temporary folder to put files that 
> are used by the test. ... But, if the test fails I want to 
> move the temporary folder away into a dedicated folder

Again, don't use a context manager, just write a try-except
that does what you want.

-- 
Greg


More information about the Python-ideas mailing list