I am using Iron Python as an added ‘for free’ tool to test the an API that wrapps comms to some custom hardware so the non-development team can play with the hardware via python.
However I can’t work out how to get .NET void func(params object[] args) to map to Python def (*args).
Here is some code to explain.
I have a type that allows injecting a logging callback to format and deal with messages is follows the signature of Console.WriteLine and Debug.WriteLine.
public class Engine
{
Action<string, object[]> _logger;
public void Run()
{
Log("Hello '{0}'", "world");
}
public void SetLog(Action<string, object[]> logger)
{
_logger = logger;
}
void Log(string msg, params object[] args)
{
_logger(msg, args);
}
}
in my IronPython code
import clr
from System import *
from System.IO import Path
clr.AddReferenceToFileAndPath(Path.GetFullPath(r"MyAssembly.dll"))
from MyNamespace import *
def logger(msg, *args):
print( String.Format(msg, args))
print( String.Format(msg, list(args)))
print( String.Format(msg, [args]))
a=[]
for i in args:
a.append(i)
print( String.Format(msg, a) )
e = Engine()
e.SetLog(logger)
e.Run()
output
Hello '('world',)'
Hello 'IronPython.Runtime.List'
Hello 'IronPython.Runtime.List'
Hello 'IronPython.Runtime.List'
I would like
Hello 'world'
Because String.Format handles your iron python objects (tuple for your first output case, lists for the last three) as single objects and is not aware that you would like the python collection to be used as
params object[]you are getting the unexpected output. The single python object/tuple is implicitly created whendef loggeris invoked.Depending on your actual use-case/style you can solve this in different ways.
The most python-y way would be expanding the arguments at their call site like Jeff explains in his answer:
If you call
loggeronly as from CLR as implementation ofAction<string, object[]>you could just haveargsbe a single (not variable) argument of typeobject[]likeIf you would like to call
loggerfrom python with variable arguments as well (and you don’t mind the back and forth conversion) you could do