Question: Best Practice? (module 'shelve')
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Wed Jan 10 02:53:17 EST 2007
In <mailman.2507.1168390525.32031.python-list at python.org>, Thomas Ploch
wrote:
>> I just wanted to know, if there is any best practice concerning
>> following code:
>>
>> […]
>>
>> def match(self, src, url):
>> self.matchDict = {}
>> self.matchDict[url] = {}
>> # The next 2 functions just add stuff to self.matchDict
>> if self.email:
>> self._addEmails(src, url)
>> self._addPatterns(src, url)
>> # Is it good practice to open, write and close the db straight
>> # away? Or is it better to leave it open until the whole program
>> # has finished, and close it then?
>> self.openDB(self.dbName)
>> self.db[url] = self.matchDict[url]
>> self.db.close()
>> # I want to del the matchDict each time so it can't grow big.
>> # Is this good, or should it be left open, too?
>> del self.matchDict
Opening an closing the DB costs time but makes sure everything is flushed
to the file. At least from the applications point of view. The data
may be still cached by the operating system before actually being written
to the file.
Do you have `self.matchDict` just for communicating between those two
methods? Why don't you use arguments and return values and a local name?
def match(self, src, url):
match_dict = dict()
if self.email:
match_dict.update(self._add_emails(src, url))
match_dict.update(self._addPatterns(src, url))
self.open_db()
self.db[url] = match_dict
self.db.close()
It's a bit shorter and `match_dict` goes out of scope automatically when
the method finishes.
Clearing `self.matchDict` doesn't buy you much anyway. At least not what
the comment suggests because it doesn't grow anymore after the end of the
method. The first action in the next call is binding the attribute to a
fresh dictionary.
>> def openDB(self, dbName=None, modeflag='c'):
>> if dbName == None:
>> self.db = shelve.open('textmatch.db', flag=modeflag)
>> else:
>> self.db = shelve.open(dbName, flag=modeflag)
def open_db(self, db_name='textmatch.db', modeflag='c'):
self.db = shelve.open(db_name, flag=modeflag)
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list