Question

I'm trying to write C# code with an embedded IronPython script. Then want to analyze the contents of the script, i.e. list all variables, functions, class and their members/methods.

There's an easy way to start, assuming I've got a scope defined and code executed in it already:

dynamic variables=pyScope.GetVariables();
foreach (string v in variables)
{
    dynamic dynamicV=pyScope.GetVariable(); /*seems to return everything. variables,     functions, classes, instances of classes*/
}

But how do I figure out what the type of a variable is? For the following python 'objects',

dynamicV.GetType() 

will return different values:

x=5 --system.Int32

y="asdf" --system.String

def func():... --IronPython.Runtime.PythonFunction

z=class() -- IronPython.Runtime.Types.OldInstance, how can I identify what the actual python class is?

class NewClass -- throws an error, GetType() is unavailable.

This is almost what I'm looking for. I could capture the exception thrown when unavailable and assume it's a class declaration, but that seems unclean. Is there a better approach?

To discover the members/methods of a class it looks like I can use:

ObjectOperations op = pyEngine.Operations;
object instance = op.Call("className");
foreach (string j in op.GetMemberNames("className"))
{
    object member=op.GetMember(instance, j);
    Console.WriteLine(member.GetType());
    /*once again, GetType() provides some info about the type of the member, but returns null sometimes*/
}

Also, how do I get the parameters to a method?

Thanks!

Was it helpful?

Solution

This isn't something that's really supported, but all of the information is there. You have two options:

  1. Cast the objects to IronPython's classes, like PythonFunction, and use the methods on them. These aren't documented, and all of the necessary methods might not be public, but you can read the source code to figure out how to use them.
  2. Use the normal Python techniques for introspection, like __class__ and __dict__. This is probably the better option.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top