Search code examples
ironpythonintrospectionnamed-parameters

IronPython: Dynamically assign python named parameters from .net's Dictionary


i want to dynamically assign parameter values coming from a .net's Dictionary instance, like this:

def Evaluator(IEvaluator):
    def Execute(self, parameters):
        a = parameters['a']
        b = parameters['b']
        c = parameters['c']
        d = parameters['d']
        e = parameters['e']
        return self.Sum(a, b, c, d, e)

    def Sum(self, a, b, c, d, e):
        return a + b + c + d + e

I would like to find a way to programatically assign variable values from the dictionary, something like this:

def Evaluator(IEvaluator):
    def Execute(self, parameters):
        return self.Sum(SetParametersByName(parameters))

    def Sum(Self, a, b, c, d, e):
        return a + b + c + d + e

I know this may not be possible exactly as i wrote, but you get the idea.

Thank you very much,

Esteban.


Solution

  • This should work:

    def Execute(self, parameters):
        return self.Sum(**parameters)
    

    If not, you'll have to convert the .NET Dictionary to a Python dict first (and let me know, so I can file a bug):

    def Execute(self, parameters):
        return self.Sum(**dict(parameters))
    

    This feature is often referred to as 'kwargs', I don't believe it has an official name.