1

I am new to hooks so I need an advice. Suppose I have a function taking as input some data and producing a plot:

def f(data, options):
   plot = produce_plot(data)
   apply_options(plot) # changing colors, style, ...
   export(plot, option.format)
   return plot

this function is not called directly by the user, but it is called inside a loop, for example:

data_categories = divide_in_category(data)
for d in data_categories: f(data, color=user_option.color, format='png')

now I want to give to the user the possibility to do more with this plot, depending on its needed. Suppose the user want to add a label and do some fits, I think a good idea is to provide a hook to access to the internals of function f. THe hook should be execute just before the export function. Question: how to do it? How to provide the internals of f inside the hook?

I cannot handle all the infinite usecases with the options argument as options.do_fit, options.add_label, ...

Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141
  • If someone searches for python hooks: http://stackoverflow.com/questions/774824/explain-python-entry-points#9615473 – guettli Oct 14 '13 at 08:28

1 Answers1

0
def f(data, options, hook = None):
   plot = produce_plot(data)
   apply_options(plot) # changing colors, style, ...
   if hook is not None:
       plot = hook(plot)
   export(plot, option.format)
   return plot

And then the user can call f with the name of a function he wrote, that will do something on plot and return a new plot.

LtWorf
  • 7,286
  • 6
  • 31
  • 45
  • ok, I can pass also `data` to the hook, but I was wondering if I can do better (for forward compatibility for exampl), for example passing all the `locals` or providing a more complex intereface. – Ruggero Turra Mar 19 '13 at 14:01