API Reference for Enthought Tool Suite 3.2.0
Using with statement for masking.
Context description: >>> context['vp'] = ... >>> context['vs'] = ... >>> context['depth'] = ...
In the code/script: >>> from with_mask import Mask >>> with Mask(depth < 20): >>> vp = 1 >>> vs = 1e-5 >>> <new-block>
which are arrays.
Context should be modified in the 'with' block.
The 'with' statement: http://www.python.org/dev/peps/pep-0343/
Usage: >>> with EXPR as VAR: # 'as VAR' is optional >>> BLOCK >>>
The with statement translates to:
>>> mgr = (EXPR) >>> exit = mgr.__exit__ >>> value = mgr.__enter__() >>> exc = True >>> try: >>> try: >>> VAR = value # Only if 'as VAR' is present >>> BLOCK >>> except: >>> exc = False >>> if not exit(*sys.exc_info()): >>> raise >>> finally: >>> if exc: >>> exit(None, None, None) >>>
A template for ensuring that a lock, acquired at the start of a block, is released when the block is left:
@contextmanager
def locked(lock):
lock.acquire()
try:
yield
finally:
lock.release()
Used as follows:
with locked(myLock):
# Code here executes with myLock held. The lock is
# guaranteed to be released when the block is left (even
# if via return or by an uncaught exception).
Example 1 rewritten without a generator:
class locked:
def __init__(self, lock):
self.lock = lock
def __enter__(self):
self.lock.acquire()
def __exit__(self, type, value, tb):
self.lock.release()
(This example is easily modified to implement the other relatively stateless examples; it shows that it is easy to avoid the need for a generator if no special state needs to be preserved.)
The idea here is we are in the block execution environment when the code with 'with' gets executed. We need the adapter to cling onto the context thats the local environment; and cling off outside the 'with' block/control.
We need to check if any change to the 'context' variable in the data context will change the context itself.
Check how the with statement works without a block and context.
- Checked, works well.
Check how the with statement works during block execution.
- Checked, Python crashes on version 2.5.0. However, after upgrading Python to 2.5.1., it works well.
| Local name | Refers to |
|---|---|
| adapt | enthought.traits.protocols.api.adapt |
| AdaptedDataContext | enthought.contexts.adapted_data_context.AdaptedDataContext |
| DataContext | enthought.contexts.data_context.DataContext |
| ICheckpointable | enthought.contexts.i_context.ICheckpointable |
| MultiContext | enthought.contexts.multi_context.MultiContext |
| ndarray | numpy.ndarray |
| sys | sys |
| with_statement | __future__.with_statement |
| WithMaskAdapter | enthought.contexts.with_mask_adapter.WithMaskAdapter |
© Copyright 2002-2009 Enthought, Inc.