Search code examples
c#python.netpython.netkeyword-argument

Call a python function with named parameter using python.net from a C# code


I want to call a python function from C# code. To do that, I used Python for .NET to call function as shown in the following lines of code

   using System;
   using Python.Runtime;

   public class Test{
        public static void Main(){
           using(Py.GIL()){
               dynamic lb = Py.Import("lb");
               dynamic result = lb.analyze("SomeValue");

                Console.WriteLine(result);
           }
        }
    }

The python function is something like this:

def analyze(source, printout = False, raw = True):
        # removed for bravity

So the question is, how can I set "raw" to False when I call the analyze function from C# code. I tried the following but it didn't work.

1. dynamic result = lb.analyze("SomeSource", raw : false); // No result

2. dynamic result = lb.analyze("SomeSource", @"raw = False"); // No result

I know it is easy to do by doing this:

   dynamic result = lb.analyze("SomeSource", False, False);

But what if there is more than six or seven named parameter, it would not be great to insert it all manually and change the one I wanted. For example, the python library that I am using have 12 named parameter with default value including two more parameters with no default value.

UPDATED I also tried:

3. dynamic result = lb.analyze("SomeSource", raw = false); // C# compilation error 

Solution

  • To apply keyword arguments use:

    lb.analyze("SomeSource", Py.kw("raw", false));

    See readme.

    Another approach is using C# keyword argument syntax that was recently added to pythonnet:

    lb.analyze("SomeSource", raw: false);