Tuesday, February 23, 2010

Python vs. Ruby

Days ago, while Guido was in PyCon, he posted a tweet about a lecture comparing Ruby & Python. That was a good one for that it mentioned pros & cons of both languages. As I tweeted before, it is evident that Ruby's syntax is much more flexible than Python, but also as Guido say, this type of flexibility (freedom) reduces the readability significantly. I confirm Guido's opinion when I review a Ruby project code. Alongside with all these, I have more reasons for choosing Python over Ruby, but I confess most of these reasons are matters of taste, rather than - so called - technical proof. Ruby testing facility is evidently very strong in compare with any other language I think. Anyway, if we decide to compare Ruby with a rival language, of course none can be like Python. I like the book name "Thinking in Python", since Python is really a method of thinking, not only a programming language.When you think in python (That is a matter of taste), you do not like overriding the whole syntax. I am not a conservative programmer, but not a unrestrained at the same time.In Ruby, you can make the string class not to be a string! How can a developer read your code so? Of course, Ruby people say no one does this, because we appreciate our freedom and do not abuse it! Anyway, review my reasons for choosing Python:

1. In Ruby you have too much freedom, which I dislike.(You may like it!)

2. I would rather to have a more readable code, than a complicated one. (You may not!)

3. I like to choose from various HTTP frameworks (TurboGears, dJango, web2Py...), rather than sticking to - although more sophisticated and complete - Rails. (Do you ?)

4. I prefre SqlAlchemy over ActiveRecord and CherryPy over Mongrel! (Taste!)

5. Google is already using Python. (Twitter uses Ruby!)

6. I dislike to have many various ways of doing the same thing. Instead, I like to be forced to do it in the most sophisticated way, as in Python. (You may prefer Perl/Ruby method of thinking!)

7. Python has a very smooth learning curve, which means I can add more developers to the project if needed. I guess I can find developers thinking in Python, more easily than ones thinking in Ruby. I think I will even struggle with Pythonic ones easier! (I learned Python in hours, but still don't know Ruby!What about you?)

8. Python is truly more documented, and mature.

All these, may vary for you or someone else. Please comment if you agree or disagree.

Tuesday, June 2, 2009

About Libraries (dll, lib, so...)?

At first, pardons for the subject. I know this is not fully related to Python, but I did not mean to have a Pythonic-only weblog. I started to found a technical weblog & since I was (am) fond of python, I chose the name.
Libraries are the most usual facts programmers face everywhere.By everywhere, I mean in every OS, every language and with every level of knowledge.I decided to write a brief but useful article about types of libraries here after a friend of mine asked about 'dll's.
in general, libraries are packages of code (usually compiled) for being used more and more. That is, libraries are the most common way of code 'reusability'.
Libraries are of 2 types in general: Static & Dynamic.
Static libraries are familiar for most C++ developers. Files with .lib extension are C static libraries. They are embedded to the executable file when compiling for deployment. So end user will never feel them from close.
Dynamic libraries has the main difference of being able to load and unload dynamically when running the executable. They usually do not attach or embed to executable file. Instead they reside on a special OS directory or beside the executable directory to be used just when they are needed. Although they can still be used as a static library.
dll means Dynamic Load Library.You can guess what dll is now. .so files are the unix variant and .dynlib Mac's one.
We have 3 different types of dll in Windows.
1. Native dlls which contain fully compiled code with OS (Windows) API calls.They usually export functions (procedure, subroutine..)
2. COM or ActiveX dlls that are OOP and support Classes instead f just Functions. They are fully compiled but a bit slower because of instantiating and destroying objects.
3. .NET dlls that are .NET assemblies (collection of classes) compiled as byte code (not native code). They also contain classes (OOP)
How you can distinguish them? Just use Microsoft Dependency walker on Windows. If the dll has exported some functions it may be native one. If it exports DllregisterServer, DllUnRegisterServer and about 3 other functions this is a COM (ActiveX) dll.
If it does not export anything, just use .NET Reflector to get the .NET class list inside the assembly.

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