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

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Sep 7 02:39:48 EDT 2017


Yury Selivanov wrote:

It would be great if you or Greg could show a couple of real-world examples showing the "issue" (with the current PEP 550 APIs/semantics).

Here's one way that refactoring could trip you up. Start with this:

async def foo():
   calculate_something()
   #in a coroutine, so we can be lazy and not use a cm
   ctx = decimal.getcontext().copy()
   ctx.prec = 5
   decimal.setcontext(ctx)
   calculate_something_else()

And factor part of it out (into an ordinary function!)

async def foo():
   calculate_something()
   calculate_something_else_with_5_digits()

def calculate_something_else_with_5_digits():
   ctx = decimal.getcontext().copy()
   ctx.prec = 5
   decimal.setcontext(ctx)
   calculate_something_else()

Now we add some more calculation to the end of foo():

async def foo():
   calculate_something()
   calculate_something_else_with_5_digits()
   calculate_more_stuff()

Here we didn't intend calculate_more_stuff() to be done with prec=5, but we forgot that calculate_something_else_ with_5_digits() changes the precision and doesn't restore it because we didn't add a context manager to it.

If we hadn't been lazy and had used a context manager in the first place, that wouldn't have happened.

Summary: I think that skipping context managers in some circumstances is a bad habit that shouldn't be encouraged.

-- Greg



More information about the Python-Dev mailing list