Dynamically registering reactive handlers at runtime
Alex Kavanagh
alex.kavanagh at canonical.com
Thu Feb 18 09:39:09 UTC 2016
On Thu, Feb 18, 2016 at 7:23 AM, Stuart Bishop <stuart.bishop at canonical.com>
wrote:
> On 12 February 2016 at 22:55, Merlijn Sebrechts
> <merlijn.sebrechts at gmail.com> wrote:
> > Hi all
> >
> >
> > We have a layer that can install a number of different packages. It
> decides
> > at runtime which packages will be installed. This layer uses the `apt`
> layer
> > which sets a state `apt.installed.<packagename>`.
> >
> > We want to react to this installed state, but we don't know what the
> > packagename will be beforehand. This gets decided at runtime. Therefore,
> we
> > can't put it in a @when() decorator.
> >
> > Is there a way to dynamically register handlers at runtime?
>
>From a Python perspective, there's nothing stopping you, at the top level
in the file, or in a function, doing:
if some-condition:
@when(...)
def some_function(...):
...
i.e. decorators don't have to be at the top level in a module/file - they
are essentially 'just' syntactic sugar for a function call on the defined
function.
@when(...)
def something():
....
is conceptually equivalent to:
def something():
...
when(...)(something)
However, I'd caution against dynamically defining the handlers, as it might
make the program/script less easy to reason about, test and debug.
I'm guessing that the possible values for packagename are known at build
time, so could you not just either list them all with their appropriate
handlers, or bundle them all into a single @when(...) if they share a
common handler?
e.g.
@when('apt.installed.packagename1')
def ...
@when('apt.installed.packagename2')
def ...
and/or
@when('apt.installed.packagename1', 'apt.installed.packagename2', ...)
def ...
Explicit tends to be more helpful than implicit. Hope this is useful
and/or helpful!
Alex.
--
Alex Kavanagh - Software Engineer
Cloud Dev Ops - Solutions & Product Engineering - Canonical Ltd
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ubuntu.com/archives/juju/attachments/20160218/1ac88df8/attachment.html>
More information about the Juju
mailing list