From 11af4b554df9a8a5c31d9dcbc1ea849b32394ba3 Mon Sep 17 00:00:00 2001 From: "Daniel M. Pelt" Date: Wed, 24 Jun 2015 18:36:03 +0200 Subject: Better way of passing options to Python plugin using inspect --- python/astra/plugin.py | 24 ++++++++++++------------ samples/python/s018_plugin.py | 13 ++++--------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/python/astra/plugin.py b/python/astra/plugin.py index ccdb2cb..891f6c9 100644 --- a/python/astra/plugin.py +++ b/python/astra/plugin.py @@ -26,22 +26,20 @@ from . import plugin_c as p from . import log +import inspect class base(object): def astra_init(self, cfg): try: - try: - req = self.required_options - except AttributeError: - log.warn("Plugin '" + self.__class__.__name__ + "' does not specify required options") - req = {} - - try: - opt = self.optional_options - except AttributeError: - log.warn("Plugin '" + self.__class__.__name__ + "' does not specify optional options") - opt = {} + args, varargs, varkw, defaults = inspect.getargspec(self.initialize) + nopt = len(defaults) + if nopt>0: + req = args[2:-nopt] + opt = args[-nopt:] + else: + req = args[2:] + opt = [] try: optDict = cfg['options'] @@ -60,7 +58,9 @@ class base(object): if not cfgKeys.issubset(reqKeys | optKeys): log.warn(self.__class__.__name__ + ": unused configuration option: " + str(list(cfgKeys.difference(reqKeys | optKeys)))) - self.initialize(cfg) + args = [optDict[k] for k in req] + kwargs = dict((k,optDict[k]) for k in opt if k in optDict) + self.initialize(cfg, *args, **kwargs) except Exception as e: log.error(str(e)) raise diff --git a/samples/python/s018_plugin.py b/samples/python/s018_plugin.py index 6677930..90e09ac 100644 --- a/samples/python/s018_plugin.py +++ b/samples/python/s018_plugin.py @@ -33,21 +33,16 @@ import six class SIRTPlugin(astra.plugin.base): """Example of an ASTRA plugin class, implementing a simple 2D SIRT algorithm. - Optional options: + Options: - 'rel_factor': relaxation factor + 'rel_factor': relaxation factor (optional) """ - required_options=[] - optional_options=['rel_factor'] - def initialize(self,cfg): + def initialize(self,cfg, rel_factor = 1): self.W = astra.OpTomo(cfg['ProjectorId']) self.vid = cfg['ReconstructionDataId'] self.sid = cfg['ProjectionDataId'] - try: - self.rel = cfg['option']['rel_factor'] - except KeyError: - self.rel = 1 + self.rel = rel_factor def run(self, its): v = astra.data2d.get_shared(self.vid) -- cgit v1.2.3