python: first impressions

Like I said before, I’ve started fiddling with Python. The approach I’m taking is starting with a command line script. I’ve been pondering writing a variable manager (duffel) to make deployment from my dev box to my staging box to dreamhost/aws/wherever I end up hosting my project (and yes, I am actually working on a project that people will be able to see and use). It was originally going to be in PHP, but instead I am writing it in Python as a way to force myself to learn it.

Surprisingly, I’ve had to do very little forcing. Despite spending most of my college years hacking PHP, I’ve found switching to Python (and back) very easy. The documentation is great and the language is very intuitive – I’d say much more so than PHP once you get a grip on the basic patterns.

Things I miss: isset() – referencing an empty key in a dictionary throws a KeyError. Instead of a simple if (isset($foo['bar'])) clause, I have to do something crazy like:

try: cp._sections[section+':cur'][x]
except KeyError:
pass
else:
print 'current value: '+cp._sections[section+':cur'][x]
Another thing that threw me off at first was the lack of a switch/case implementation, but I’ll definitely live. Also the shorthand if-else isn’t really shorthand at all…

Things I love: the brevity, notably in string operations and regular expressions. The lack of brackets is also amazing. Years ago I wrote some rudimentary pythong basically using an existing script as a crutch, and I was infinitely bothered by the lack of brackets. Then my other nut descended, and I started reading code using tabulation. I now love not having to use brackets.

Function objects do it for me.

Keyword argument passing also rocks my socks.

The icing, though, is the standard library. Holy fuck.

op = OptionParser()
op.add_option('-a', '--action', dest='action')
op.add_option('-p', '--package', dest='package')
(options, args) = op.parse_args()
You kiddin me?!! If you write Python cli scripts and don’t use this, you are really missing out. It doesn’t do that much, but it sure makes things easier.

Also, the ConfigParser class makes me remember the “If you have the right tools, you aren’t really working” saying.

You can see the source (nowhere near finished) for duffel in my svn.

Leave a Reply