Loading .NET assemblies into Python


My love for Python grows every day while I’m at work where I’m learning the integration possibilities between Python and .NET using IronPython. It’s particularly amazing how, from within a Python script, you can instantiate .NET objects; make calls to them, manipulate the data brought back and fire it off again.

One of the possibilities afforded by this feature is that you can use the scripting language in your business layer as a rules engine. I’m not talking about workflow (although that’s also a possibility) but that all the rules in your business layer are written as a script. This means that if the Business Analyst or the customer is unhappy with the rule or wants to tweak it you can change the appropriate script without have to re-compile or even stopping the application!

OK, so how do you add a .NET object to a Python script so that it can be manipulated? Well, let’s assume you have an object Customer which contains 2 properties, Name and LastPurchaseDate and a method GetCustomer.

namespace ExampleCompany

{

 

public class Customer

{

private string name;

public string Name

{

 

get { return name; }

set { name = value; }

}

 

private DateTime lastPurchaseDate;

public DateTime LastPurchaseDate

{

get { return lastPurchaseDate; }

set { lastPurchaseDate = value; }

}

 

public void GetCustomer(int index)

{

//TODO

}

}

}

Now to add this object to your Python script is very easy (note: my script is being interpreted by IronPython which has a CLR object it knows about)

import clr

clr.AddReference(“ExampleCompany”)

from ExampleCompany import Customer

x = Customer()

x.GetCustomer(14)

print x.Name

print x.LastPurchaseDate

First I import the clr library because IronPython can only directly import some of the .NET libraries and my class needs to be explicitly referenced. I add the namespace to the clr (the DLL must be in the sys.path directory) and from that namespace I import the class I want to use. I could have also used import * and imported everything in the namespace.

After that it’s a simple matter of instantiating a new instance of my class and called the method before printing out the returned name and LastPurchaseDate.

Information and Links

Join the fray by commenting, tracking what others have to say, or linking to it from your blog.


Other Posts
Building an RTS game
Talk on CardSpace and The Laws of Identity

Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!