Saturday, March 19, 2011

Why I'm starting to truly love #Python

I've been busy the last two weeks putting the finishing touches on everything TweetFree: TweetFree Relay Server, TweetFree Network Server, and TweetFree Mobile have all kept me crazy busy and working in two or three languages all while learning some new concepts like oAuth. I have to say, it's been quite a ride.

The amount of code I've had to write wasn't bad for what it accomplishes. In fact, the mobile client probably ended up containing more code than either the Relay or Network server but that's probably because I did a lot of crap I didn't have to since I'm not very familiar with Java (which is what the mobile client is written in).

But here's the real reason for this post: I want to say I am falling in love (and I mean toe curling, cuddling together, long term relationship type love) with the Python programming language. If you've not tried the language yet, you might not understand why I'm so head over heals in love with it but let me give you an example:

When I originally wrote TweetFree Netork Server, I did so in PHP because that's the web language I am most comfortable in. The code was OK, but when I was dealing with Twitter's oAuth, it got a little tricky. Overall, the Network Server ended up being a little over 360 lines of code.

Tonight, I decided to see how Python would handle it so I fired up my text editor and starter to write. I'll be the first to say that I am NOT a Python programmer and generally have to look almost everything up. But even at my semi-novice level, I was able to rewrite the entire server in about 30 minutes with only 110 lines of code. And we're not talking hard to read, obfuscated code here, we're talking code that probably is a little to 'chatty' and could be optimized even more.

Can you see now why I'm in love with Python? Readability also comes into play to. Let me give you one more example:

Let's say we have a HTML form that passes a username, password, and group name through a POST request. To prepare those for use in PHP, I'd generally use the following code:

$username = striplashes($_POST['username']);
$password = stripslashes($_POST['password');
$grp = stripslashes($_POST['group']

That takes the POST variables and sticks them safe local variables that have been properly escaped and are ready to use in my script. No, it's not difficult code at all and it's easy to understand for even a novice PHP programmer. But look at the same Python code:

myForm = cgiFieldStorage()
username = myForm["username"].value
password = myForm["password"].value
grp = myForm["group"].value

Yes, there's an extra line of code, but it's not too much and I think the readability of the code went way up.

Am I ready to switch all my web development to Python now? Not yet. But I am rather intrigued with this powerful language that keeps the simple stuff simple and makes the hard stuff easy.

No comments: