[Python-Dev] PEP 377 : Allow enter() methods to skip the statement body : real world case (original) (raw)

Nick Coghlan ncoghlan at gmail.com
Fri May 4 15:34:05 CEST 2012


On Fri, May 4, 2012 at 10:17 PM, Pierre Chanial <pierre.chanial at gmail.com> wrote:

Hello,

PEP 377 has been rejected for lack of use cases. Here is one. I'm writing an MPI-based application and in some cases, when there is less work items than processes, I need to create a new communicator excluding the processes that have nothing to do. This new communicator should finally be freed by the processes that had work to do (and only by them). If there is more work than processes, the usual communicator should be used. A neat way to do that would be to write: with filtercomm(comm, nworkitems) as newcomm: ... do work with communicator newcomm... the body being executed only by the processes that have work to do. It looks better than: if comm.size < nworkitems: newcomm = getnewcommunicator(comm, nworkitems) else: newcomm = comm if comm.rank < nworkitems: try: ... do work with communicator newcomm... finally: if comm.size < nworkitems: newcomm.Free() Especially since I have to use that quite often.

However, your original code is not substantially better than:

with filter_comm(comm, nworkitems) as newcomm:
    if newcomm is not None:
        ... do work with communicator newcomm...

Where filtercomm is a context manager that:

It isn't that there are no use cases for skipping the statement body: it's that the extra machinery needed to allow a context manager to do so implicitly is quite intrusive, and the control flow is substantially clearer to the reader of the code if the context manager is instead paired with an appropriate nested if statement.

Cheers, Nick.

-- Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-Dev mailing list