mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
Updates to the with-statement:
- New semantics for __exit__() -- it must re-raise the exception if type is not None; the with-statement itself doesn't do this. (See the updated PEP for motivation.) - Added context managers to: - file - thread.LockType - threading.{Lock,RLock,Condition,Semaphore,BoundedSemaphore} - decimal.Context - Added contextlib.py, which defines @contextmanager, nested(), closing(). - Unit tests all around; bot no docs yet.
This commit is contained in:
parent
87a8b4fee5
commit
1a5e21e033
12 changed files with 609 additions and 96 deletions
|
@ -2173,6 +2173,32 @@ for name in rounding_functions:
|
|||
|
||||
del name, val, globalname, rounding_functions
|
||||
|
||||
class ContextManager(object):
|
||||
"""Helper class to simplify Context management.
|
||||
|
||||
Sample usage:
|
||||
|
||||
with decimal.ExtendedContext:
|
||||
s = ...
|
||||
return +s # Convert result to normal precision
|
||||
|
||||
with decimal.getcontext() as ctx:
|
||||
ctx.prec += 2
|
||||
s = ...
|
||||
return +s
|
||||
|
||||
"""
|
||||
def __init__(self, new_context):
|
||||
self.new_context = new_context
|
||||
def __enter__(self):
|
||||
self.saved_context = getcontext()
|
||||
setcontext(self.new_context)
|
||||
return self.new_context
|
||||
def __exit__(self, t, v, tb):
|
||||
setcontext(self.saved_context)
|
||||
if t is not None:
|
||||
raise t, v, tb
|
||||
|
||||
class Context(object):
|
||||
"""Contains the context for a Decimal instance.
|
||||
|
||||
|
@ -2224,6 +2250,9 @@ class Context(object):
|
|||
s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
|
||||
return ', '.join(s) + ')'
|
||||
|
||||
def __context__(self):
|
||||
return ContextManager(self.copy())
|
||||
|
||||
def clear_flags(self):
|
||||
"""Reset all flags to zero"""
|
||||
for flag in self.flags:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue