Wednesday, May 6, 2009

Why do I use Python?

Python, as a really good dynamic language, is ideal for various types of tasks. Less complexity, more readability and versatility makes Python my favorite programming language. Python simply understands what I mean.

a=b=c=4

a, b, c=45, 76, 98

if a in range(1,10):

if 'a' and 'g' in 'gorilla':

These are very simple. But there is more to Python. Dumping a text file:

f=open('/Users/kamyar/numbers.txt','rt')
for i in f:
print i
f.close()

Dumping a website html:

import urllib2
f=urllib2.urlopen('http://www.yahoo.com')
for i in f:
print i
f.close()

'for' loop and iterators are very flexible in Python. they can even iterate on XML files and network resources. The other strength of this language is string/sequence manipulation:

a='abcdefg'
a[1:3] #### result: 'bc'
a[-3:-1] #### result: 'ef'
a[1:5:2] #### result: 'bd'











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'.

Monday, May 4, 2009

What does a dynamic language look like?

This intro is for those developers have not yet the chance of struggling with a great dynamic language like Python or Ruby. They may find out the different paradigm of programming in dynamic languages.
Here, anything is an Object. The concept of 'Object' is far away from what we are used to call in pure OOP languages like C# & Java. For instance, in Python, a class or type is an object! You know in C# we declare variables of classes and then construct them to make an object. The concept seems confusing. For clarification, I have to write some example:

s='This is a test'
t=type(s)
class myClass(t):
pass

As you can see, we have the type of string (str) in a variable named t.As you may know, python inherits a parent class using parenthesis.But here, we have not provided the compiler with name of the class. Instead, we have given a variable containing the class. We could define myClass type as follows:

class myClass(str):
pass

I think you may have found out the real meaning of 'dynamic' language. In static languages like C#, we cant by no means do this. Even reflection does not do the same thing for us, since we have to do anything on the fly, and we cant add code to our function.

Type t = typeof(string)
.
.
.
public class myClass : t ' >>>>>>> Error!
{
}

Sunday, May 3, 2009

Some people think that dynamic typing is bad! This is because most of them get confused with Static Typing & Strict Typing. They think dynamic typing means 'No Type'.In Python, for example, we have strict typing, but most of times, the type is guessed by the compiler itself.

>>> a=5

>>> type(a)

int

>>> b=5.43

>>> type(b)

float

>>> c='test'

>>> type(c)

str

The best part of the fact is that you can have a complex type (e.g. Dictionary) which has different key types (despite C# or so).

>>> myDic={'test':45 , 56.7:'sd'}

>>> type(myDic.keys()[0])

str

>>>type(myDic.keys()[1])

float

>>> type(myDic['test'])

int

>>> type(myDic[56.7])

str

Saturday, May 2, 2009

Python vs. C#

Just for lazy programmers who try to change the reality to fit their laziness, from now on, I will put some sample codes comparing Python and C#. Lazy developers usually claim about the existence of dynamic languages and new programming concepts, without considering their success during these years and even facts that even Micro$oft tries to support them more and more. DLR an F#, and even declarative parts of new C# proves that.
This is a simple binary serialization of a simple dictionary in both languages. We need an array of bytes containing serialized data (e.g. to put in a RDBMS field). After that, I added a line to tell us the length of stream. After comparing 'lines of code' and complexity, you can even compare the 'Binary' size in C# and Python:

C# Code:

using System;

using System.Collections.Generic;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

namespace TestDicPack

{

class Program

{

static void Main(string[] args)

{

MemoryStream mem = new MemoryStream();

Dictionary<string, int> dic = new Dictionary<string, int>();

dic.Add("a", 2);

dic.Add("b", 3);

BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(mem, dic);

byte[] result = mem.ToArray();

Console.WriteLine(result.Length);

Console.ReadLine();

}

}

}

Result:

1380

Python Code:

import pickle

dic={'a':2,'b':3}

result=pickle.dumps(dic,2)

print len(result)


Result:

22