[IronPython] Determine the classes/interfaces a Python implements

Michael Foord fuzzyman at voidspace.org.uk
Mon Dec 15 13:20:18 PST 2008

Hi Jeff,

Probably the easiest way of doing this is to define a Python function 
that uses issubtype. You can use this as a delegate from the C# side 
(warning untested):

ScriptScope scope = engine.CreateScope();
ScriptSource imports = engine.CreateScriptSourceFromString("from System 
import ISomething", SourceCodeKind.Staatements);
ScriptSource source = engine.CreateScriptSourceFromString("lambda x: 
issubtype(x, ISomething)", SourceCodeKind.Expression);
Func<object, bool> Implements = (scope)source.Execute(scope);

bool result = Implements(some_object);

Note that issubtype will barf if you give it anything other than a type, 
so it may make more sense to define a function with exception handling 
and pull it out of the scope instead.


Michael Foord

Jeff Slutter wrote:
> I have a Python script that creates a class within it. This Python class
> is derived off of a class, or interface, I made in C# - something like:
> class MyClass(Test.MainForm.IScript):
>     ...
> Now, back in C#, I have gotten access to "MyClass" by:
> object myclass = someScope.GetVariable("MyClass");
> Is there a way to determine either:
> a) what classes/interfaces MyClass implements OR
> b) if it implements a specific class/interface
> I want to know if the "object myclass" is supposed to implement
> Test.MainForm.IScript or not.
> I don't want to create an instance of MyClass as this would cause
> problems, executing things I'm not ready to execute.
> Also, related but not as important, implementing an interface (as above)
> doesn't cause any compiler errors if I'm missing functions - is there a
> way to enforce this?
> Thanks,
> Jeff
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com


More information about the Users mailing list