Can't pass C # dictionary to ironPython method as parameter

I need to pass a list of parameters stored in a dictionary to a function implemented by the ironPython class.

I have prepared a minimal example that reproduces the error:

        // C# Side
        var runtime = Python.CreateRuntime();
        dynamic test = runtime.UseFile("test.py");

        // Here the parameters dictionary is instantiated and filled
        var parametersDictionary = new Dictionary<string, int>();
        parametersDictionary.Add("first", 1);

        // The Python 'x' instance is called passing parameter dictionary
        var result = test.x.ReturnFirstParameter(parametersDictionary);

      

Now the Python code:

# Python side

# Class 'Expression' definition
class Expression(object):
    def ReturnFirstParameter(self, **parameters):
        return parameters['first']

# Class 'Expression' instantiation
x = Expression()

      

When I run the program, I get the following exception:

ReturnFirstParameter() takes exactly 1 argument (2 given)

      

The first parameter is "i", but it seems like it ignores its 2 parameters, "self" and a dictionary.

I tried changing the dictionary for other parameters and it works well. The problem only occurs when getting parameter **.

I really appreciate your help!

Esteban.

+3


source to share


1 answer


This should work to just remove the **

before parameters

in your Python code:

class Expression(object):
    def ReturnFirstParameter(self, parameters):
        return parameters['first']

      

**

should be used when you are passing named parameters to a function and your C # code will be passing a dictionary.

Your C # code will call the function like this:



x.ReturnFirstParameter({'first': 1})

      

To work with the **parameters

call must be

x.ReturnFirstParameter(first=1)

      

There might be a way to do this using ironpython, but I'm not sure how.

+1


source







All Articles