::beware!::

April 25th, 2011 by hamish download the zooToolBox

Sometimes I wish I could go back in time and slap some sense into myself. One of the very first things I discovered when I was learning python was operator overloading. I’d not used a language with such power before and stupidly I put this newfound knowledge to use in all sorts of crazy ways.

Today I found an early piece of code I wrote. Its a useful chunk of code – parses config files.

Anyway I wanted to add some functionality to the code. See the config files it parses are often written by hand, and the format supports C-style comments. Currently the parser throws away the comments which is no drama if you just need read support – but a feature request came up that would require the writing of these files from a tool. So I need to preserve comments as best as I can.

Not a big drama to add the functionality except that part of the code I ended up having to touch involved one of the operator overloads – in this case the [] operator (__getitem__ in python). The existing overload was done in a super weird way (what I wanted to slap “past me” for). I made it so you could do this:

f = ConfigFile( 'd:/something.txt' )
f.read()
f[0, 2, -1, 9]

Which would navigate the config file document hierarchy. Why?! Well, probably because I was a n00b and figured it’d be “cool”. SLAP!

Anyway, whats the point here? Well, I guess what I’m trying to say is (apart from don’t write idiotic code) – if you’re going to overload operators be really really careful. Tracking down where the code is used is hard. You can’t really grep your codebase for anything in particular – after all, the whole point of operator overloading is so the interface to the action looks like a standard language operator. In this particular case it wasn’t a big deal – the code is used in only a few places. But if this code had wider use, it would’ve been a nightmare.

This is pretty obvious to anyone who has been coding for awhile – but after this recent reminder I figured a little PSA might save others some pain

Share

This post is public domain

This entry was posted on Monday, April 25th, 2011 at 20:33 and is filed under main. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.