Skip to content

Commit

Permalink
easier operator hooks
Browse files Browse the repository at this point in the history
This adds the ability to pass optional custom operators to the import
hook context and have the operators installed for the duration of the
context.
  • Loading branch information
sccolbert committed Jul 3, 2013
1 parent 3536569 commit 2aaf3c9
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
37 changes: 35 additions & 2 deletions enaml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,42 @@ def createLock(self):
#------------------------------------------------------------------------------
# Import Helper
#------------------------------------------------------------------------------
def imports():
def imports(operators=None, union=True):
""" Lazily imports and returns an enaml imports context.
Parameters
----------
operators : dict, optional
An optional dictionary of operators to push onto the operator
stack for the duration of the import context. If this is not
provided, the default Enaml operators will be used. Unless a
custom model framework is being used (i.e. not Atom), custom
operators will typically not be needed.
union : bool, optional
Whether to union the operators with the operators on the top
of the operator stack. The default is True and is typically
the correct choice to allow overriding a subset of the default
Enaml operators.
Returns
-------
result : context manager
A context manager which will install the Enaml import hook
(and optional operators) for the duration of the context.
"""
from enaml.core.import_hooks import imports
return imports()
if operators is None:
return imports()

from contextlib import contextmanager
from enaml.core.operators import operator_context

@contextmanager
def imports_context():
with imports():
with operator_context(operators, union):
yield

return imports_context()
10 changes: 9 additions & 1 deletion enaml/core/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,15 +535,23 @@ def op_delegate(klass, binding):


@contextmanager
def operator_context(ops):
def operator_context(ops, union=False):
""" Push operators onto the stack for the duration of the context.
Parameters
----------
ops : dict
The dictionary of operators to push onto the stack.
union : bool, optional
Whether or to union the operators with the existing operators
on the top of the stack. The default is False.
"""
if union:
new = dict(__get_operators())
new.update(ops)
ops = new
__operator_stack.append(ops)
yield
__operator_stack.pop()
Expand Down

0 comments on commit 2aaf3c9

Please sign in to comment.