Tuesday, May 5, 2009

What does a dynamic language look like? (Part 2)

Following my last post about dynamic language capabilities, I want to mention some interesting feature of Python at which I wondered a lot. We have 2 'Sequence' (Collection in C#) types in python: Tuple (array-like immutable type) and List. Also, we have a Dictionary type just like C#'s Dictionary (or old Hashtable). As you may now, in most languages you can define functions with floating number of arguments at end. For example in C#:

  public static void TestFunc(params int[] args)
  {
      foreach (var i in args)
     {
        Console.WriteLine(i);
      }
  }

TestFunc(5,2,7);

TestFunc(new int[] {1,2,3});

Result:

5

2

7

1

2

3

This is 2 limitations here:

1. If we wanted to use various type arguments, we would not be able to use this method, since C# Collections must be the same data type, despite Python's.

def TestFunc(*args):

    print args

TestFunc(5,'test',7)

TestFunc(*(1,2,3)) ##########>>>> or TestFunc(*[1,2,3])

result:

(5, 'test' , 7)

(1, 2, 3)

2. C# does not support 'Named-arguments' except for 'Attribute' class declarations' constructor. VB.NET still supports named arguments for function declaration. Anyway, what if I want to send different (numerous) variables of various types to a function without explicitly specifying them? Consider the following Python code:

def TestFunc(**args):

    print args

TestFunc(a=23,b=45)

Result:

{'a': 23, 'b': 45}

As you can guess, the compiler makes a Dictionary type (with string keys) on the fly from named arguments. Keys are the name of arguments and values are their values.Very interesting! But you may ask when shall we use this feature? If you are a strict OOP programmer you may find this feature useless at first galance. But wait, have you ever used CherryPy? It is one of the most famous and great Http Frameworks for Python. When an http request has been sent to a server equipped with a CherryPy based web site, it will give the developer all the parameters as a function argument:

http://www.example.com/testpage?firstname=John&lastname=Smith

In cherrypy we have:

def testpage(firstname,lastname):

    print firstname,lastname

Result: 

John Smith

But we could use a more generalized syntax liek this:

def testpage(**args):

    if 'firstname' and 'lastname' in args:   

         print args['firstname'],args['lastname']

   Great? Note that Python understands what do you mean by the 'and'.

No comments:

Post a Comment