[Python-Dev] PEP 550 v4 (original) (raw)

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Sep 6 20:00:39 EDT 2017


Nathaniel Smith wrote:

Literally the first motivating example at the beginning of the PEP ('def fractions ...') involves only generators, not coroutines, and only works correctly if generators get special handling. (In fact, I'd be curious to see how Greg's {push,pop}localstorage could handle this case.)

I've given a decimal-based example, but it was a bit scattered. Here's a summary and application to the fractions example.

I'm going to assume that the decimal module has been modified to keep the current context in a context var, and that getcontext() and setcontext() access that context var.

THe decimal.localcontext context manager is also redefined as:

class localcontext():

   def __enter__(self):
      push_local_context()
      ctx = getcontext().copy()
      setcontext(ctx)
      return ctx

   def __exit__(self):
      pop_local_context()

Now we can write the fractions generator as:

def fractions(precision, x, y):
   with decimal.localcontext() as ctx:
     ctx.prec = precision
     yield Decimal(x) / Decimal(y)
     yield Decimal(x) / Decimal(y ** 2)

You may notice that this is exactly the same as what you would write today for the same task...

-- Greg



More information about the Python-Dev mailing list