From 88a53fbdd1e24ee7bd0a05d80b3b3b80c388945e Mon Sep 17 00:00:00 2001 From: llllllllll Date: Tue, 10 Nov 2015 22:04:32 -0500 Subject: [PATCH] ENH: update context_tricks Moves _nop_context to context_tricks under the name nop_context. Uses an explicit object for the actual context manager in callback manager. --- zipline/utils/context_tricks.py | 39 ++++++++++++++++++++++----------- zipline/utils/events.py | 15 +++---------- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/zipline/utils/context_tricks.py b/zipline/utils/context_tricks.py index 6d76879c..c4746616 100644 --- a/zipline/utils/context_tricks.py +++ b/zipline/utils/context_tricks.py @@ -1,4 +1,12 @@ -from contextlib import contextmanager +@object.__new__ +class nop_context(object): + """A nop context manager. + """ + def __enter__(self): + pass + + def __exit__(self, *excinfo): + pass def _nop(*args, **kwargs): @@ -44,17 +52,22 @@ class CallbackManager(object): exiting another block """ def __init__(self, pre=None, post=None): - pre = pre if pre is not None else _nop - post = post if post is not None else _nop - - @contextmanager - def _callback_manager_context(*args, **kwargs): - try: - yield pre(*args, **kwargs) - finally: - post(*args, **kwargs) - - self._callback_manager_context = _callback_manager_context + self.pre = pre if pre is not None else _nop + self.post = post if post is not None else _nop def __call__(self, *args, **kwargs): - return self._callback_manager_context(*args, **kwargs) + return _ManagedCallbackContext(self.pre, self.post, args, kwargs) + + +class _ManagedCallbackContext(object): + def __init__(self, pre, post, args, kwargs): + self._pre = pre + self._post = post + self._args = args + self._kwargs = kwargs + + def __enter__(self): + return self._pre(*self._args, **self._kwargs) + + def __exit__(self, *excinfo): + self._post(*self._args, **self._kwargs) diff --git a/zipline/utils/events.py b/zipline/utils/events.py index a9cd6744..7c9f9e1b 100644 --- a/zipline/utils/events.py +++ b/zipline/utils/events.py @@ -20,6 +20,8 @@ import datetime import pandas as pd import pytz +from .context_tricks import nop_context + __all__ = [ 'EventManager', @@ -169,17 +171,6 @@ def _build_time(time, kwargs): return datetime.time(**kwargs) -@object.__new__ -class _nop_context(object): - """A nop context manager. - """ - def __enter__(self): - pass - - def __exit__(self, *excinfo): - pass - - class EventManager(object): """Manages a list of Event objects. This manages the logic for checking the rules and dispatching to the @@ -196,7 +187,7 @@ class EventManager(object): self._create_context = ( create_context if create_context is not None else - lambda *_: _nop_context + lambda *_: nop_context ) def add_event(self, event, prepend=False):