Created
September 25, 2013 20:51
-
-
Save pberkes/6705859 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
import inspect | |
from traits.api import * | |
from traits import trait_notifiers | |
class ChangeEventPrinter(object): | |
def __init__(self): | |
self.indent = 1 | |
def pre_tracer(self, obj, name, old, new, handler): | |
change_pfx = '-' * self.indent*2 + '>' | |
change_msg = "{pfx} '{name}' changed from {old} to {new} in '{class_name}'" | |
print change_msg.format(pfx=change_pfx, name=name, | |
old=old, new=new, | |
class_name=obj.__class__.__name__) | |
calling_pfx = ' '*(self.indent*2+1) | |
calling_msg = "{pfx} CALLING: '{handler}' in {source}" | |
print calling_msg.format(pfx=calling_pfx, handler=handler.__name__, | |
source=inspect.getsourcefile(handler)) | |
self.indent += 1 | |
def post_tracer(self, obj, name, old, new, handler, exception=None): | |
self.indent -= 1 | |
pfx = '<' + '-' * self.indent*2 | |
if exception: | |
exception_msg = ' [EXCEPTION: {}]'.format(exception) | |
else: | |
exception_msg = '' | |
exit_msg = "{pfx} EXIT: '{handler}'{exception}" | |
print exit_msg.format(pfx=pfx, handler=handler.__name__, | |
exception=exception_msg) | |
if self.indent == 1: | |
@contextmanager | |
def print_change_events(): | |
printer = ChangeEventPrinter() | |
trait_notifiers.set_change_event_tracers(pre_tracer=printer.pre_tracer, | |
post_tracer=printer.post_tracer) | |
try: | |
yield | |
finally: | |
trait_notifiers.clear_change_event_tracers() | |
class Foo(HasTraits): | |
""" Test traits class with static and dynamic listeners. | |
Changing `baz` triggers a dynamic listeners that modifies `bar`, which | |
triggers one dynamic and one static listeners. | |
""" | |
bar = Float | |
baz = Float | |
fuz = Float | |
def _bar_changed(self): | |
pass | |
@on_trait_change('bar') | |
def _on_bar_change_notification(self): | |
pass | |
@on_trait_change('baz') | |
def _on_baz_change_notification(self): | |
self.bar += 1 | |
@on_trait_change('fuz') | |
def _on_fuz_change_notification(self): | |
self.bar += 1 | |
raise Exception('Crash') | |
if __name__ == '__main__': | |
foo = Foo(bar=3) | |
with print_change_events(): | |
foo.baz = 4 | |
foo.fuz = 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment