Wednesday, July 9, 2008

Pythonist Rants

Its interesting to see how Pythonist does some stuffs and then suddenly you find that doing that in some other language wasn't a bad idea either ....and then...suddenly (again) it dawns on you that many things could be done in Python that is IMPOSSIBLE to duplicate exactly .

Lets say you have a vector in C++ that you need to remove an item if it fits a certain scenario.

The layman's way is to do the following in C++ (not using algorightm stl ;-))

vector::iterator ptr;
for (ptr = abc.begin(); ptr != abc.end(); ptr++)
{
if (*ptr == "red")
{
abc.erase(ptr)
if (ptr == abc.end()) break;
ptr--
}
}


This is one of the way Pythonist does it :-


for x in abc[:]: # this means makes a copy of abc
if x == "red" :
acb.remove(x)

Yup, coming from C++, one's mentality one would wonder why we didnt use that similar method in Python in C++. However, this wouldn't work in C++ without futher modifications, this is because the "erase" is not taking a value but rather the iterator which means if you do this on the original vector but you passed in the iterator instance from the copy, it wouldn't work.


Then there is the story of smtpd.py. Its basically a smtp proxy/server skeleton that supports the basic commands. And how does one go and implement the "MAIL FROM", "RCPT TO", "DATA" method? The normal thinking would be to do a method/function for each of these commands and then there is the switch or if-else statement working on a read buffer.

How did smtpd.py do it?

method = getattr(self, 'smtp_' + command, None)
if not method:
self.push('502 Error: command "%s" not implemented' % command)
return
method(arg)

Introspection! It basically appends the command read and massaged from the buffer and append to the "smtp_" and invoke the method ....

No comments:

Post a Comment