1

In circuits 3.1.0, is there a way to set at runtime the channel for a handler? An useful alternative would be to add a handler at runtime and specify the channel.

I've checked the Manager.addHandler implementation but couldn't make it work. I tried:

self._my_method.__func__.channel = _my_method_channel
self._my_method.__func__.names = ["event name"]
self.addHandler(self._my_method)
Matias SM
  • 364
  • 3
  • 7

1 Answers1

0

Yes there is; however it's not really a publically exposed API.

Example: (of creating event handlers at runtime)

@handler("foo")
def on_foo(self):
    return "Hello World!"


def test_addHandler():
    m = Manager()
    m.start()

    m.addHandler(on_foo)

This is taken from tests.core.test_dynamic_handlers

NB: Every BaseComponent/Component subclass is also a subclass of Manager and has the .addHandler() and .removeHandler() methods. You can also set the @handler() dynamically like this:

def on_foo(...):
    ...

self.addHandler(handler("foo")(on_foo))

You can also see a good example of this in the library itself with circuits.io.process where we dynamically create event handlers for stdin, stdout and stderr.

James Mills
  • 18,669
  • 3
  • 49
  • 62
  • Great! thank you. For the sake of completeness, I must say that these work only with free functions (and alike), not with instance methods (which, of course, can be workarounded by using lambdas) – Matias SM Aug 15 '15 at 22:51
  • Yes; ``.addHandler()`` expects a function decorated with ``handler()`` and then binds this to the component. – James Mills Aug 16 '15 at 00:12