def f(x): """This function knows nothing of numpy""" return 2 * math.sin(x) + math.cos(x) import numpy def numpy_math_context(): """This function returns a context where 'math' is a reference to numpy.""" return {'math': numpy} # this essentially vectorizes the function f = context_function(f, numpy_math_context) # so that this works print f(numpy.array([0, 0.5, 1]) * numpy.pi) ############################################################################# # Example 2 ############################################################################# accumulation_dict = {'total': 0} def accumulator_factory(): """Return the same dictionary on every function call""" return accumulation_dict
""" from traits.api import HasTraits, on_trait_change from codetools.contexts.api import DataContext, context_function class ListeningDataContext(DataContext): """ A simple subclass of DataContext which listens for items_modified events and pretty-prints them.""" @on_trait_change('items_modified') def print_event(self, event): print "Event: items_modified" for added in event.added: print " Added:", added, "=", repr(self[added]) for modified in event.modified: print " Modified:", modified, "=", repr(self[modified]) for removed in event.removed: print " Removed:", removed def f(x, t=3): """ A function which will fire add, modify and delete events. """ y = x+2 y += 1 z = '12' del z return y f = context_function(f, ListeningDataContext) f(3)
from traits.api import HasTraits, on_trait_change from codetools.contexts.api import DataContext, context_function class ListeningDataContext(DataContext): """ A simple subclass of DataContext which listens for items_modified events and pretty-prints them.""" @on_trait_change('items_modified') def print_event(self, event): print("Event: items_modified") for added in event.added: print(" Added:", added, "=", repr(self[added])) for modified in event.modified: print(" Modified:", modified, "=", repr(self[modified])) for removed in event.removed: print(" Removed:", removed) def f(x, t=3): """ A function which will fire add, modify and delete events. """ y = x + 2 y += 1 z = '12' del z return y f = context_function(f, ListeningDataContext) f(3)
# Example 1 ############################################################################# import math def f(x): """This function knows nothing of numpy""" return 2*math.sin(x) + math.cos(x) import numpy def numpy_math_context(): """This function returns a context where 'math' is a reference to numpy.""" return {'math': numpy} # this essentially vectorizes the function f = context_function(f, numpy_math_context) # so that this works print f(numpy.array([0, 0.5, 1])*numpy.pi) ############################################################################# # Example 2 ############################################################################# accumulation_dict = {'total': 0} def accumulator_factory(): """Return the same dictionary on every function call""" return accumulation_dict