Saturday, November 7, 2009

My first python

Well my first python code in a long time. My first was modifying a zope photo album module to work after an dist-upgrade of a Debian GNU/Linux system.

Any who--I'm working on a project which will store e-mail addresses in a relational DB. I am contemplating storing the the email in two parts--the user name and the domain name. When storing the domain name, I'm considering storing the domain name in reverse order (i.e. "roansbitsnbytes.blogspot.com" stored as "com.blogspot.roansbitsnbytes") for potentially faster indexed searching. Of course this complicates other aspects of the program (at least on the db side), but I'll deal with that as the design comes.

One of my concerns with storing the domain name this way, is not requiring the client program to have to deal with how the e-mail addresses are going to be stored. I know reversing the domain name can be done in a stored SQL based procedure, but I figure another language can probably do it more concisely (and quicker). PostgresSQL allows you to use stored functions created in Python. After a little digging around, here is the one liner I came up with to reverse the domain name:

".".join(((domainname.split('.'))[::-1]))

where domainname is a string passed to my function in PostgreSQL.

I like how concise this is. When I started I was pretty sure I would be using a split and join command. I just wasn't sure if it could all be done with one line of code. Python's slice notation for mutable sequences (aka the list of domain names created using the split command) makes this one liner nice and neat.

See this url: http://docs.python.org/library/stdtypes.html#typesseq-mutable for more on mutable sequences. Unfortunately, I can't find the original link that led me to this solution.

No comments:

Post a Comment