Getting a Jump-Start with IronPython

Exclusive offer: get 50% off this eBook here
Expert Python Programming

Expert Python Programming — Save 50%

Best practices for designing, coding, and distributing your Python software

$26.99    $13.50
by Darrell Hawley | May 2009 | Open Source

As a .NET developer, you’ve probably heard IronPython mentioned in a blog post or an article, but do you know what it is? IronPython is Microsoft’s implementation of the Python language. Python is known for readability and its’ proponents claim that applications written with Python are done faster, use fewer lines of code and are more maintainable than those written using more traditional languages. The great thing about IronPython is that you get the advantages of the language, while being able to leverage your knowledge of the .NET framework. In this article by Darrell Hawley, we will cover a few basic aspects of IronPython and use them to create a Windows Form.

Where do you get it?

Before getting started, you’ll need to download IronPython 2.0.1 (though the contents of this article could just as easily be applied to past or even future versions). The official IronPython site is www.codeplex.com/ironpython. Here you’ll find not only the IronPython bits, but also samples, source code, documentation and many other resources. After clicking on the "Downloads" tab at the top you will be presented with three download options: IronPython.msi, IronPython-2.0.1-Bin.zip (the binaries) or IronPython-2.0.1-Src.zip (the source code). If you already have CPython installed—the standard Python implementation—the binaries are probably your best bet. You simply unzip the files to your preferred installation directory and you’re done. If you don’t have CPython installed, I recommend the IronPython.msi file since it comes prepackaged with portions of the CPython Standard Library.

Expert Python Programming

Figure 1. IronPython installation directory.

There are a few items I would like to highlight in the IronPython installation directory displayed in Figure 1. The first is the FAQ.html file. This covers all of your basic IronPython questions, from licensing questions to implementation details. Periodically reviewing this while you’re learning IronPython will probably save you a lot of frustration. The second item of importance is the two executables, ipy.exe and ipyw.exe. As you probably guessed, these are what you use to launch IronPython; ipy.exe is used for scripts and console applications while ipyw.exe is reserved for other types of applications (Windows Forms, WPF, etc). Lastly, I’d like to draw your attention to the Tutorial folder. Inside the Tutorial folder, you’ll find a Tutorial.html file in addition to a number of other files. The Tutorial.html file is a comprehensive review of what you need to know to get started with IronPython. If you want to be quickly productive, be sure to at least review the tutorial. It will answer many of your questions.

Visual Studio or a Text Editor?

One thing that neither the ReadMe nor the Tutorial really covers is the tooling story. While Visual Studio 2008 is a viable Python development tool, you may want to consider other options. Personally, I bounce between VS and SciTE, but I’m always watching for new tools that might improve my development experience.  There are a number of IDEs and debuggers out there and you owe it to yourself to investigate them. Sometimes, however, Visual Studio IS the right tool for the job. If that’s the case then you’ll need to install the Visual Studio SDK from http://www.microsoft.com/downloads/details.aspx?FamilyID=30402623-93ca-479a-867c-04dc45164f5b&displaylang=en.

Let’s Write Some Code!

To get started, let’s create a simple python script and execute it with ipy. In a new file called "sample.py" (Python files are indicated by a ".py" extension), type "print ‘Hello, world’". Open a command window, navigate to the directory where you saved sample.py and then call ipy.exe passing "sample.py" as an argument. Figure 1 displays what you might expect to see in the console window.

Expert Python Programming

Figure 2. Executing a script using the comand line

Not that executing from the Command Line isn’t effective, but I prefer a more efficient approach.  Therefore I’m going to use SciTE, an editor I briefly mentioned earlier, to duplicate the example in Figure2. Why SciTE? I get syntax highlighting, I can run my code simply by hitting F5 and the stdout is redirected to SciTE’s output window. In short, I never have to leave my coding environment. If you performed the above "hello, world" example in SciTE, the example would look like Figure 2.

Expert Python Programming

Figure 3. Executing a script using SciTE

Congratulations! You’ve written your first bit of Python code! The problem is it doesn’t really touch any .NET namespaces. Fortunately, this is not a difficult thing to do. Figure 3 shows all the code you need to start working with the System namespace.

Expert Python Programming

Figure 4. You only need a single of code to gain access to the System namespace

With that simple import statement, we now enjoy access to the entirety of the System namespace. For example, to access the String class we simply would type System.String. That’s great for getting started but what happens when we want to use something like the Regex class? Do we have to type System.Text.RegularExpressions.Regex?

Expert Python Programming

Figure 5. Using .NET regular expressions from IronPython

No! The first line of Figure 5 introduces a new form of the import statement that only imports the specific items you want. In our case, we only want the Regex class. The code in line 3 demonstrates creating a new instance of the Regex class. Note the lack of a "new" keyword. Python considers "new" redundant since you have to include parentheses anyways. Another interesting note is the syntax—or is it the lack of syntax—for creating a variable. There’s no declaration statement or type required. We simply create a name that we set equal to a new instance of the Regex class. If you’ve ever written any PHP or classic ASP, this should feel pretty familiar to you.  Finally, the print statement on line 6 produces the output shown in Figure 6.

Expert Python Programming

Figure 6. Output from the Regex example

The last example was easy because IronPython already holds a reference to System and mscorlib. Let’s push our limits and create a simple Windows form. This requires a bit more work.

Expert Python Programming

Figure 7. Using the clr module to add a reference

A Quick Review of Python Classes

Figure 7 introduces the clr module as a way of adding references to other libraries in the Global Assembly Cache (GAC). Once we have a reference, now we can import the Form, TextBox and Button classes so we can start constructing our GUI. Before we do that though, we have a couple of concepts we need to cover.

Expert Python Programming

Figure 8. Introducing classes and methods

Up until this point, we really haven’t needed to create any classes or methods. But now that we need to create a form we’re going to need both. Figure 8 demonstrates a very simple class and an equally simple method. I think it’s clear that the "class" keyword defines a class and the "def" keyword defines a method. You probably correctly assumed that "(object)" after "MyClass" is Python’s way of expressing inheritance. The "pass" keyword, however, may not be immediately obvious. In Python, classes and methods cannot be empty. Therefore, if you have a class or method that you aren’t quite ready to code yet, you can use the "pass" statement until you are ready.

A more subtle characteristic of Figure 8 is the whitespace. In Python we indent the contents of control structures with four spaces. Tabs will also work, but by convention four spaces are used. In our example above, since "my_method" has no preceding spaces, it’s clear that "my_method" is not part of "MyClass".

So how would we make "my_method" a class method? Logically, you would think that simply deleting the "pass" statement under "MyClass" and indenting "my_method" would be enough, but that isn’t the case. There’s one more addition we need to make.

Expert Python Programming

Figure 9. Creating a class method

As Figure 9 demonstrates, we need to pass "self" as a parameter to "my_method". The first—and sometimes the only—parameter in a class method’s parameter list must always be an instance of the containing class. By convention, this parameter should be named "self", though you could call it anything you’d like. Why the extra step? That’s because Python values the explicit over the implicit. Hiding this detail from the developer is at odds with Python’s philosophy.

Creating a Windows Form

Now that we have an understanding of classes, methods and whitespace, Figure 10 continues our example from Figure 7 by creating a blank form.

Expert Python Programming

Figure 10. Creating a blank form

The code in Figure 10 should be fairly understandable. We create the "MyForm" class by inheriting from "System.Windows.Forms.Form". We create a new instance of "MyForm" and pass the resulting object to the "Application.Run()" method. The only thing that may give you pause is the "__init__()" method. The "__init__()" method is what’s called a magic method. Magic methods are designated with double underscores on either end of the method name and are rarely called directly. For instance, when the code in Line 10 of Figure 10 executes, the "__init__()" method defined in "MyForm" is actually being called behind the scenes.

Expert Python Programming

Figure 11. Populating the form with controls and handling an event handler

Figure 11 adds a lot of code to our application, most of which isn’t very interesting. The exception here is the Click event of the goButton. In C#, the method would get passed as an argument in the constructor of a new EventHandler. In IronPython, we simply add a function with the proper signature to the Click event.  Now that we have a button that will respond to a click, Figure 12 shows a modified version of our regular expression sample code from earlier inserted into the click method. Note the "__str__()" magic method is the equivalent of ToString().

Expert Python Programming

Figure 12. Populating click with our regular expression example

When we run the code, you should see the form displayed in Figure 13. You can enter dates into the top textbox, press the button and either True or False will appear in the lower textbox indicating the results of the IsMatch() function.

Expert Python Programming

Figure 13. Completed form

Conclusion

During the course of one brief article, you went from knowing little of IronPython to using it to build Windows Forms. We were able to move so quickly because we leveraged your existing .NET knowledge.  We spent most of our time talking about the very intuitive Python syntax. Go through sample or even production code you've written in the past and duplicate it in IronPython. You’ll find working with familiar .NET libraries will speed your learning process, making it more fun. Before you know it, Python will become second-nature!

Expert Python Programming Best practices for designing, coding, and distributing your Python software
Published: September 2008
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :


Darrell Hawley

Darrell Hawley is a Microsoft C# MVP developing engineering software while researching Python and agile development techniques. He has streamlined business processes as well as administered company networks and SQL Server installations. He also has proficiencies in code generation, web services, ASP.NET, Smart Clients, VB.NET, Visual Basic, VBA, VBScript and ASP. He is a board member of the Ann Arbor .NET Developers Group and frequently speaks at user groups and conferences around Ohio and Michigan.

Books From Packt

 

  Practical Plone 3: A Beginner's Guide to Building Powerful Websites
Practical Plone 3: A Beginner's Guide to Building Powerful Websites

Learning SQL Server 2008 Reporting Services
Learning SQL Server 2008 Reporting Services

Expert Python Programming
Expert Python Programming

Small Business Server 2008 – Installation, Migration, and Configuration
Small Business Server 2008 – Installation, Migration, and Configuration

Expert Cube Development with Microsoft SQL Server 2008 Analysis Services
Expert Cube Development with Microsoft SQL Server 2008 Analysis Services

VSTO 3.0 for Office 2007 Programming
VSTO 3.0 for Office 2007 Programming

Plone 3 Theming
Plone 3 Theming

SOA Patterns with BizTalk Server 2009
SOA Patterns with BizTalk Server 2009

 

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
7
f
B
y
A
W
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software