Monday, July 17, 2006

IronPython and the moving API

Last week the IronPython team released IronPython .0 beta 9. This should be the last beta before the release candiate.  Also  they  say they have finally locked down  the Hosting API. This has an impact on what I have been working on, which involves hosting the interpreter within an ASP.NET handler. Thankfully the final Hosting API has returned to a more pythonic API rather than imho, the ugly API of beta 8.

With each beta release, there seem to be just enough changes in how to do things that writing an article on IronPython that will work with later beta's is a challenge. Even the IronPython team have been having trouble keeping their tutorials that ship with the beta in sync.

For example, on the IronPython mailinglist, Michael Foord pointed out a link to an article on IronPython. It is well written and has some interesting code examples that could attract a .NET programmer to give IronPython a go. I am not sure when the article was written but at least one code example doesn't work as a python list is no longer automatically converted to an array when passed as a argument to a .NET class. So to get this example to work for beta 9:

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import *

class MyForm(Form):
def __init__(self):
Form.__init__(self)

Button1 = Button()
Button1.Top = 10
Button1.Left = 10
Button1.Text = "One"

Button2 = Button()
Button2.Top = 50
Button2.Left = 10
Button2.Text = "Two"

ctrls = [Button1, Button2]
self.Controls.AddRange(ctrls)

f = MyForm()
Application.Run(f)

You need to modify the line:
ctrls = [Button1, Button2]
to:
ctrls = System.Array[System.Windows.Forms.Control]( (Button1, Button2) )

You will also need to add
import System
after the
import clr
line.

The author of the article provides the above syntax as an alternative solution, but as of beta 9 it's the only solution. I can understand why these changes have needed to happen so late in the beta programme, but it's a shame we miss a chance to bring more programmers under the spell of Python because the code didn't work.

No comments: