Skip to content

Commit

Permalink
ENH: update context_tricks
Browse files Browse the repository at this point in the history
Moves _nop_context to context_tricks under the name nop_context.
Uses an explicit object for the actual context manager in callback
manager.
  • Loading branch information
llllllllll committed Nov 11, 2015
1 parent b6310db commit 88a53fb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 24 deletions.
37 changes: 25 additions & 12 deletions zipline/utils/context_tricks.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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
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 _ManagedCallbackContext(self.pre, self.post, args, kwargs)

@contextmanager
def _callback_manager_context(*args, **kwargs):
try:
yield pre(*args, **kwargs)
finally:
post(*args, **kwargs)

self._callback_manager_context = _callback_manager_context
class _ManagedCallbackContext(object):
def __init__(self, pre, post, args, kwargs):
self._pre = pre
self._post = post
self._args = args
self._kwargs = kwargs

def __call__(self, *args, **kwargs):
return self._callback_manager_context(*args, **kwargs)
def __enter__(self):
return self._pre(*self._args, **self._kwargs)

def __exit__(self, *excinfo):
self._post(*self._args, **self._kwargs)
15 changes: 3 additions & 12 deletions zipline/utils/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import pandas as pd
import pytz

from .context_tricks import nop_context


__all__ = [
'EventManager',
Expand Down Expand Up @@ -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
Expand All @@ -196,7 +187,7 @@ def __init__(self, create_context=None):
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):
Expand Down

0 comments on commit 88a53fb

Please sign in to comment.