UPDATE: Well, that didn’t take long. My solution works, but there’s a better way. Create the connection in main(), and create separate *cursors* for each Host. Cursors are cheap, and you reuse the connection. Thanks to Brend on #python (irc.freenode.net) for the enlightenment.
Python has been a wonderful language to get to know so far. However, one thing I didn’t really miss about Java and C++ were the decisions that are kind of forced upon you when you have various objects working together in a program, controlled by code in a “main” function. Here’s one decision I was faced with that took more thinking than I’d like to admit to make.
I have a class, we’ll call it “Host”. Of course, there are also methods for that class, like Host.record_name() and Host.update_mac() and the like. These methods are just wrappers around some SQL.
I also have, of course, a “main” function, which is where we create instances of Host and call the methods we need on the objects.
The question now is, where exactly should we create the handle to the database? There would appear to be 4 choices (without getting overly absurd):
- In main() and then pass the handle to the class’s ‘init()’
- In main(), but pass the handle to each method of any object that needs it.
- In Host.init(), so methods can refer to it without creating it themselves.
- Inside the individual methods themselves.
I chose option #3. The only part that bothers me about it is that a new “Host” is created, and then destroyed, for each of a couple thousand lines of a file. Hence, there is the overhead of setting up and tearing down a database connection a couple thousand times every time this script is run. I’m not sure (yet) what the cost of this will be.
Certainly, the cost will be less than if I did it for each *method* that was called, so that insures that option 4 is probably not the right way to go.
The semantics involved in creating the handle in main() and passing it to Host’s init seemed less than straightforward to me. It seemed there was the potential for main to pass in a copy of the handle at object instantiation time, have the object be destroyed when it’s done doing its work, taking the connection with it, and then main still thinks it’s a useful handle and tries to pass it to the next object that needs to be created. If that’s not the case, then what is the status of this thing that main created? What will happen if main tries to pass it to another object?
Of course, this problem would also exist if we passed it to each method that needed it. It would also be more overhead, and it would seem needlessly draconian, especially since *every* method of the object in question would need it.
If I’ve misunderstood something, or have made a poor choice, feel free to clarify/flame/enlighten me in the comments 🙂
Technorati Tags: python, database, programming, development, sql, internet, technology, opensource