Archive for September 2009

Recently I posted a short article about how to do simple configuration with IronPython. I figured that it would be easier with .NET 4.0 thanks to the dynamic support. And it is. Using Visual Studio 2010, create a new Console Application. Add one file called Configuration.py and set the copy output property to Copy Always. Here’s the Python code for that file:

configuration.Text = "Hello from IronPython"

configuration.Count = 4

And here’s the code for the Program class:

class Program

{

staticvoid Main(string[] args)

{

dynamic configuration = ConfigureFromIronPython();

for (int i = 0; i < configuration.Count; i++)

{

Console.WriteLine(configuration.Text);

}

Console.WriteLine("Press any key to exit...");

Console.ReadKey(true);

}

privatestatic dynamic ConfigureFromIronPython()

{

dynamic configuration = new ExpandoObject();

ScriptEngine engine = Python.CreateEngine();

ScriptScope scope = engine.CreateScope();

scope.SetVariable("configuration", configuration);

engine.ExecuteFile("Configuration.py", scope);

return configuration;

}

}

For that to work you need add references to IronPython and Microsoft.Scripting (there’s a CTP of IronPython for .NET 4.0 that you can get here.) You’ll also need a few using statements:

using System.Dynamic;

using IronPython.Hosting;

using Microsoft.Scripting.Hosting;

The two things that make this work are the ExpandoObject and the dynamic keyword. The ExpandoObject is a dynamic property bag that allows us to set and get members at runtime as needed. The dynamic keyword means that .NET will resolve the properties at runtime (rather than the traditional behaviour of checking at compile time.) The result is (I think) more simple and elegant than the configuration code to which I’ve become accustomed.