Skip to content

Commit 88a53fb

Browse files
author
llllllllll
committed
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.
1 parent b6310db commit 88a53fb

File tree

2 files changed

+28
-24
lines changed

2 files changed

+28
-24
lines changed

zipline/utils/context_tricks.py

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
from contextlib import contextmanager
1+
@object.__new__
2+
class nop_context(object):
3+
"""A nop context manager.
4+
"""
5+
def __enter__(self):
6+
pass
7+
8+
def __exit__(self, *excinfo):
9+
pass
210

311

412
def _nop(*args, **kwargs):
@@ -44,17 +52,22 @@ class CallbackManager(object):
4452
exiting another block
4553
"""
4654
def __init__(self, pre=None, post=None):
47-
pre = pre if pre is not None else _nop
48-
post = post if post is not None else _nop
55+
self.pre = pre if pre is not None else _nop
56+
self.post = post if post is not None else _nop
57+
58+
def __call__(self, *args, **kwargs):
59+
return _ManagedCallbackContext(self.pre, self.post, args, kwargs)
4960

50-
@contextmanager
51-
def _callback_manager_context(*args, **kwargs):
52-
try:
53-
yield pre(*args, **kwargs)
54-
finally:
55-
post(*args, **kwargs)
5661

57-
self._callback_manager_context = _callback_manager_context
62+
class _ManagedCallbackContext(object):
63+
def __init__(self, pre, post, args, kwargs):
64+
self._pre = pre
65+
self._post = post
66+
self._args = args
67+
self._kwargs = kwargs
5868

59-
def __call__(self, *args, **kwargs):
60-
return self._callback_manager_context(*args, **kwargs)
69+
def __enter__(self):
70+
return self._pre(*self._args, **self._kwargs)
71+
72+
def __exit__(self, *excinfo):
73+
self._post(*self._args, **self._kwargs)

zipline/utils/events.py

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
import pandas as pd
2121
import pytz
2222

23+
from .context_tricks import nop_context
24+
2325

2426
__all__ = [
2527
'EventManager',
@@ -169,17 +171,6 @@ def _build_time(time, kwargs):
169171
return datetime.time(**kwargs)
170172

171173

172-
@object.__new__
173-
class _nop_context(object):
174-
"""A nop context manager.
175-
"""
176-
def __enter__(self):
177-
pass
178-
179-
def __exit__(self, *excinfo):
180-
pass
181-
182-
183174
class EventManager(object):
184175
"""Manages a list of Event objects.
185176
This manages the logic for checking the rules and dispatching to the
@@ -196,7 +187,7 @@ def __init__(self, create_context=None):
196187
self._create_context = (
197188
create_context
198189
if create_context is not None else
199-
lambda *_: _nop_context
190+
lambda *_: nop_context
200191
)
201192

202193
def add_event(self, event, prepend=False):

0 commit comments

Comments
 (0)