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

Sunday, April 26, 2009

ZeroC ICE 3.3.1 has been released. it is great. I succeeded to install it on Windows, Linux, FreeBSD but not yet Mac OS X. I want to migrate my whole framework core to Python.

C# , Web Services (1), Windows, .NET Framework 2

will be migrated to:

Python 2.6, ICE, FreeBSD (OS Independent)

What is your idea?

Friday, April 24, 2009

Yea, I love python, I preferred to name my recently made weblog to Python Prophet, since I want to Invite others to it.