IronPython – The Language – Variables, Functions and Classes

In my previous post I talked about how to get started with IronPython, in this post I want to follow up with some very basic information about the actual language and some tips to enable you to start reading sample code. This post won’t make you an expert, but it should be enough to get you going.

One of the great things about IronPython and IronRuby is that there are already a huge amount of resources online about the language. A good starting point (apart form this post of course) is http://docs.python.org/ which contains the documentation for the Python language.  One problem with that approach is that there are minor differences different Python and IronPython.

Defining a variable

Defining a variable in IronPython seems a logical place to start.  The easiest way to play around with the language is by using the interactive console (ipy.exe).

To define a variable, you simply say = , for example:

>> x = 1

This creates a variable called x, of type integer (it has inferred the type) with the value of 1. As Python is a dynamic language, the way it handles variables is sightly different than you would expect compared to a static language like C#.  While Python is still a strongly typed language, it is perfectly legal to do this following:

>>> x = 1
>>> print x
1
>>> x = “Hello World”
>>> print x
Hello World
>>>

What happens is that within the first statement we create an integer object and assign it to x, in the second statement we create a string object and assign it to x, removing the reference to x. However, if we try and mix the types then it throws an exception, here we are trying to add an int to a string.

>>> x = “Hello World” + 1
Traceback (most recent call last):
  File , line unknown, in Initialize##24
TypeError: unsupported operand type(s) for +: ‘str’ and ‘int’

Python does know the type of the variable, it only uses it when it is actually required at runtime (late-binding) as far as I can tell.  For example, using the type function will return the correct type of the variable.

>>> print type(x)

So what does this mean while you are developing, well, it makes unit testing a lot easier as you don’t need to worry so much about getting an object of the extract type – it just needs to look like the type. Also, code is more generic as it doesn’t depend on the extract type.   However, you do run the risk of the type being wrong which is only found at runtime – but your automated tests will catch that right?

Creating a function

Now we can define variables, the next step is to define functions (methods). While Python is a dynamic language, it still has very strict language rules which must be followed, including it’s important on whitespace and tabbing unlike C#.

To define a method, we start with def, we then provide a name for our method, we add a number of parameters separated by commas, no need to include the type as Python will work it out for itself. Finally, we need to end the line with a colon :.  Next, we need to fill in the body of the method, the most important thing is to tab in to indicate the body, we can then write a number of lines of code, if the method should return a value then we can include that as the last line. To mark the end of the method, you have another carriage return.

Below we create a function called x, with the parameters y and z. In the method body, we just add the two and print them to the output (the console).

>>> def x(y, z):
…     print y + z

We can then simply call this method, notice that we can use both ints and strings and the correct action is taken.
>>> x(1,2)
3
>>> x(“Hello”, “World”)
HelloWorld

As we create the method, if we get something wrong then an error will be returned to alert us. Below I attempted to create a method but I forgot to include the colon at the end of the method.

>>> def x(y, z)
  File “”, line 1
    def x(y, z)
            ^
SyntaxError: unexpected token ‘

Similarly, if we do not indent the function body an error is returned.

>>> def x(y, x):
… print y + x
  File “”, line 2
    print y + x
    ^
IndentationError: expected an indented block

Below is just an example of how to return a value from a method.

>>> def x(y,x):
…     return y + x

>>> y = x(1,2)
>>> print y

Finally, python allows you to create functions within functions, which will have local scope. Great for code re-use and readability!

>>> def y():
…     def x(y, z):
…             print y + z
…     x(1,2)
…     x(“Hello”, “World”)

>>> y()
3
HelloWorld

Creating a Class

Creating a class is very similar to creating a function. The syntax is class ():  In the brackets, we can simply define all of the base classes.

>>> class MyClass(object):

We can then define function on the class in the same way, however one change is that we need to include self (similar to this in C#) as the first parameter of the method.
…     def PrintHello(self):
…             print “Hello!”
…     def Method2(self, x):
…             print “TWO TWO TWO”

To initialise the class, we simply say this:
>>> x = MyClass()

We can then call methods on it:

>>> x.PrintHello()
Hello!
>>> x.Method2(“Parameter”)
TWO TWO TWO

If we want to know all the methods on a class, we can do a dir.  Everything with a double underscore is an internal method. In the class we can define the actions to take when they get called.

>>> dir (x)
[‘Method2’, ‘PrintHello’, ‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__doc__’, ‘__getattribute__’, ‘__hash__’, ‘__init__’, ‘__module__’, ‘__name__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__str__’, ‘__weakref__’]

For example:

>>> class InitClass:
…     def __init__(self):
…             print “Created”

>>> i = InitClass()
Created

Just to sum up, Python is a full featured language, I haven’t even touch onto some of the features of the language but hopefully it will provide you some insight into the code.

Technorati Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *