From 0c89fc5d70b2cd9a199400a6731637bfc554e952 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 4 Feb 2019 21:25:42 +1030 Subject: [PATCH] pylightning: use different decoration for init msg. The next patch wants to decorate the methods with a compulsory 'usage' option, which doesn't make sense for init. So I wanted to change the init to its own decoration. Made-to-work-by: @cdecker Signed-off-by: Rusty Russell --- contrib/plugins/helloworld.py | 2 +- contrib/pylightning/lightning/plugin.py | 29 +++++++++++++------------ 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/contrib/plugins/helloworld.py b/contrib/plugins/helloworld.py index 3e0e22cb0..d2a4f4d85 100755 --- a/contrib/plugins/helloworld.py +++ b/contrib/plugins/helloworld.py @@ -19,7 +19,7 @@ def hello(plugin, name="world"): return s -@plugin.method("init") +@plugin.init() def init(options, configuration, plugin): plugin.log("Plugin helloworld.py initialized") diff --git a/contrib/pylightning/lightning/plugin.py b/contrib/pylightning/lightning/plugin.py index 848c7663e..033f1cdfd 100644 --- a/contrib/pylightning/lightning/plugin.py +++ b/contrib/pylightning/lightning/plugin.py @@ -25,7 +25,7 @@ class Plugin(object): """ def __init__(self, stdout=None, stdin=None, autopatch=True): - self.methods = {} + self.methods = {'init': (self._init, MethodType.RPCMETHOD)} self.options = {} # A dict from topics to handler functions @@ -43,7 +43,7 @@ class Plugin(object): self.rpc_filename = None self.lightning_dir = None self.rpc = None - self.init = None + self.child_init = None def add_method(self, name, func): """Add a plugin method to the dispatch table. @@ -158,6 +158,16 @@ class Plugin(object): return f return decorator + def init(self, *args, **kwargs): + """Decorator to add a function called after plugin initialization + """ + def decorator(f): + if self.child_init is not None: + raise ValueError('The @plugin.init decorator should only be used once') + self.child_init = f + return f + return decorator + def _exec_func(self, func, request): params = request['params'] sig = inspect.signature(func) @@ -265,12 +275,6 @@ class Plugin(object): return msgs[-1] def run(self): - # Stash the init method handler, we'll handle opts first and - # then unstash this and call it. - if 'init' in self.methods: - self.init = self.methods['init'] - self.methods['init'] = (self._init, MethodType.RPCMETHOD) - partial = "" for l in self.stdin: partial += l @@ -322,12 +326,9 @@ class Plugin(object): for name, value in options.items(): self.options[name]['value'] = value - # Swap the registered `init` method handler back in and - # re-dispatch - if self.init: - self.methods['init'], _ = self.init - self.init = None - return self._exec_func(self.methods['init'], request) + # Dispatch the plugin's init handler if any + if self.child_init: + return self._exec_func(self.child_init, request) return None