devxlogo

Python + .NET = IronPython

Python + .NET = IronPython

t’s not often you see Microsoft adopting a language from the world of Open Source Software (OSS), but IronPython is just such a project and has gathered a growing following among several groups working on Longhorn and associated technologies. IronPython is the creation of Jim Hugunin, now a Microsoft employee, who also created JPython/Jython.

The Python language has been around for almost 15 years and was created by Guido van Rossum who now carries the title of BDFL (Benevolent Dictator For Life). Quoting from the Python website:

“Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor of a language called ABC. Guido is Python’s principal author, although it includes many contributions from others. The last version released from CWI was Python 1.2. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI) in Reston, Virginia where he released several versions of the software. Python 1.6 was the last of the versions released by CNRI. In 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. Python 2.0 was the first and only release from BeOpen.com.”

What You Need
IronPython and version 2.0 of the .NET runtime

Interest in the Python language has grown considerably over the last several years, with a number of high profile projects, such as Chandler, choosing it over Java or some other equally capable language. Tacit support within the Microsoft camp has sprung up in different areas such as the Scripting Guys column on TechNet and lately the Avalon team. Do a search for Python on the Microsoft site, and you’ll get lots of hits including a Python Scripts Master Index page.

IronPython started out as an exercise in proving why the .NET platform was not conducive to implementing a dynamic programming language. Like many such efforts the end result was exactly the opposite of the original intent. Not only is the Common Language Runtime (CLR) conducive, it runs Python code even faster than the original C-based version.

What Is Python?
The Python language is part of a growing family of dynamic programming languages that include names like Boo (another .NET-based dynamic language), Groovy (a Java-based scripting language), Scheme, and Ruby. Wikipedia defines a dynamic programming language as “a kind of programming language in which programs can change their structure as they run: functions may be introduced or removed, new classes of objects may be created, [and] new modules may appear.”

Standard releases of Python include an interactive console that lets developers enter commands interactively, displaying the results and thus making it easy to try out the syntax of a new command or see the output of a call to particular function. The standard Python library includes a wide array of built-in functions, types, exceptions, and constants. The latest version of the Python library documentation describes each of these in great detail.

Everything in Python is an object and thus exhibits all the behavior you would expect from an object, including things such as attributes, methods and inheritance. Arguments to a function call are passed as object references, extending this concept one step further. The design of the language, its small size, and its simple syntax make it easy to teach new developers the basic concepts of object orientation and how to use objects to build a complete program. Each release of the language includes a complete Python Tutorial updated to reflect any new features added since the last version.

I took a personal interest in Python a little over a year ago while trying to decide which computer language to use to teach my then 14-year-old son the basics of programming. One requirement I had for choosing a language was that it had to run on multiple operating systems, including Windows 98 (because that was what my son’s hand-me-down computer was running). Python filled that requirement. I was particularly attracted to Python’s interactive interpreter which lets you try out language features and get immediate results.

For newcomers to the Python language, the most immediately obvious feature is the use of whitespace. In Python, whitespace?the indentation of lines of code?is significant and takes the place of curly brackets or other “block” syntax conventions used in other programming languages. If you don’t adhere to this convention, the interpreter complains and refuses to execute your code.

For example, the code to print the square of the numbers 1 through 12 in C#, VB.NET and Python would be:

C#

   for (int inum=1; inum

VB.NET

   For inum = 1 to 12      Debug.print inum**2   Next inum   

Python

   For inum in range(12):       Print num**2

Why Python?
Python is a language of shortcuts. Things that take multiple lines of code in other languages take fewer lines in Python. String manipulation is a particularly strong suit for Python. When defining a string both single and double quotes work. To escape special characters such as carriage return you must use the backslash () character followed by the decimal equivalent. The concept of slices makes it easy to grab a part of a string as in:

   >>> Str = 'This is a string'   >>> Str[2:6]   'is i'   >>>Str[-4]   'r'   

When you need to build a really long string that spans several lines of text you can use the triple quote construct to surround the entire line as in:

   VeryLongString = '''   Now is the time for all good men to come   To the aid of their countrymen. '''

Strings can span multiple lines of text as long as they are enclosed in triple quotes.'''

While Python is a dynamic language it is still strongly typed in a sense?meaning every object has a type. Python includes a number of built-in types such as lists, tuples, and dictionaries for simplifying many traditional programming tasks. On the other hand you don't declare variables with a type as you do in other languages such as C# or Java. The Python interpreter takes care of that for you sometimes to a fault. If you use the same name for a variable in two different parts of a program the first gets overwritten by the second?an obvious potential for hard-to-find bugs.

As a scripting language Python does the job of letting you build quick little programs in a short amount of time and test them interactively to make sure they work correctly. The Python library includes a multitude of pre-defined functions that make the job of coding much easier. You can also find numerous sample examples code on the Web, including code for such tasks as automating Word and Excel, interacting with Active Directory, and accessing the Windows Management Interface (WMI).

.NET Python

?
Figure 1. IronPython Console: The IronPython Console app provides an interactive interpreter where you can try out parts of the language.

The first public mention of IronPython was at the PyCON conference held in March of 2004 in Washington, DC. In this paper, Jim Hugunin describes the work he did to implement the full semantics of the Python language on top of the Common Language Runtime?either Microsoft's .NET version or the Mono platform. The paper goes on to describe his research and the test results.

Early implementations of IronPython worked on version 1.1 of the .NET runtime. Later releases target the upcoming version (2.0). As of this writing the latest IronPython version is 0.7.5 and requires the .NET Framework Version 2.0 Redistributable Package Beta 2.

The interactive console includes a built-in command (dir) that lists all the functions within a module. Figure 1 shows a list of all the functions included in the sys module. Python's help function has not been implemented in this version of IronPython.

A Sample IronPython Project
Scripting languages are all about automating repetitive tasks. Python fits right in with that description becuase it simplifies the process of "gluing" things together. The Python standard library includes many different functions that reduce the implemention of complex programs to a simple task of connecting pieces together. For example, one command that demonstrates the simplicity of Python is urlretrieve. It accepts two arguments: URL and Directory. So to grab the home page from yahoo.com and save it in the file temp.html, you would enter:

   >>> from urllib import urlretrieve   >>> urlretrieve('http://www.yahoo.com/','temp.html')   

Project Gutenberg has been around for quite some time and includes a large library of public domain literature. Recently, the site has started to provide audio book versions of some of their more popular books. You can choose from either a version read by a computer (not recommended unless you truly like listening to a computer-generated voice) or a version read by a human.

One of the available audio book collections includes a number of Sir Arthur Conan Doyle's Sherlock Holmes novels, read by one of his countrymen. Each book in the collection consists of chapters stored as individual files. Some of the audio books offer multiple versions of the same chapters at different fidelity levels in case you don't need or don't have the bandwidth to support the higher quality sound and larger file sizes.

For example, the downloadable sample code for this article is an application that shows how to download chapters from one of the Sherlock Holmes books on the Project Gutenberg site. The following code shows how to retrieve a URL and write it out to the MyDir directory:

      print 'Downloading...',      for x in range(num):         print 'Downloading chapter', str(v)+'...',         url = source+bok+hz+zfill(str(v), 2)+'.mp3'         dir2 = MyDir+'\'+str(v)+'.mp3'         v = v + 1         try:            urlretrieve(url, dir2)         except:            makedirs(MyDir)

Adding code to pop up a Windows Forms dialog to ask for user input is pretty straightforward, but note that you do need to import the System (sys) namespace and load the appropriate assemblies:

?
Figure 2. MP3 Audio Book GUI: This simple Audio Book Download application retrieves a list of files from the Project Gutenberg Web site and downloads them with a single button click.
   import sys   sys.LoadAssemblyByName("System.Drawing")   sys.LoadAssemblyByName("System.Windows.Forms")      from System.Windows.Forms import *   from System.Drawing import *      frm = Form(Text="IronPython Coding Sample",          HelpButton=True,      MinimizeBox=False, MaximizeBox=False)

Using the sys.LoadAssemblyByName method to load a CLR assembly is the mechanism that opens up IronPython to the entire .NET runtime. After loading the assembly, you must still use the import function to load the appropriate functions. The command from System.Windows.Forms import * instructs the Python interpreter to get a reference to all (*) the available methods and enumerations within the Drawing namespace.

Predicting the future is never easy, but the future of Python at Microsoft is pretty clear. In the world of open source software the Python language is very much alive and has a vibrant community that embraces and supports it. That will serve to further its adoption both within Microsoft and in the growing .NET developer community as a viable alternative to traditional scripting languages.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist