Question

Is there a generic method of converting a Dynamic Language Runtime (DLR) object into a string representation? For example, here is an example where obj is checked for a couple of specific types (Python, in this case):

        if (obj is IronPython.Runtime.List) {
          repr = ((IronPython.Runtime.List)obj).__repr__(
                  IronPython.Runtime.DefaultContext.Default);
        } else if (obj is IronPython.Runtime.PythonDictionary) {
          repr = ((IronPython.Runtime.PythonDictionary)obj).__repr__(
                  IronPython.Runtime.DefaultContext.Default);

But I would really like to get a representation of obj in its own language (IronPython, IronRuby, etc) and without having to compare to each and every type. obj.ToString() doesn't give a good representation for most objects.

Was it helpful?

Solution

AFAIK, there's no one common method to convert DLR objects to their representative string representations. It is language dependent and they are not implemented the same unfortunately.

With IronPython at least, you could always just get a reference to the Builtin module then call the str() (or repr()) function on your objects.

var engine = Python.CreateEngine();
dynamic obj = engine.Execute("[1, 2, 3, 4, 5]");
dynamic builtin = engine.GetBuiltinModule();
string repr = builtin.str(obj);

Of course you could call the function within the script too.

string repr = (string)engine.Execute("str([1, 2, 3, 4, 5])");

Another option would be to use one of the many operations defined in the IronPython.Runtime.Operations namespace.

string repr = IronPython.Runtime.Operations.PythonOps.ToString(obj);

I'm not very familiar with IronRuby but calling to_s() on some objects seems to work sometimes. Otherwise, it actually returns a .NET object where to_s does not exist and is not very reliable. I think it's easier to do it within the script.

var engine = Ruby.CreateEngine();
string repr = (string)engine.Execute("[1, 2, 3, 4, 5].to_s");

You might want to look around and see if there are other methods you could use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top