Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store and use a large text-file in python

Tags:

python

boggle

I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.

What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?

like image 746
Adam Plumb Avatar asked Oct 01 '08 16:10

Adam Plumb


2 Answers

If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can:

import dictionary

dictionary.words[whatever]

where dictionary.py has:

words = {}

# read file and add to 'words'
like image 67
Rodrigo Queiro Avatar answered Oct 01 '22 04:10

Rodrigo Queiro


Even though it is essentially a singleton at this point, the usual arguments against globals apply. For a pythonic singleton-substitute, look up the "borg" object.

That's really the only difference. Once the dictionary object is created, you are only binding new references as you pass it along unless if you explicitly perform a deep copy. It makes sense that it is centrally constructed once and only once so long as each solver instance does not require a private copy for modification.

like image 20
Jeremy Brown Avatar answered Oct 01 '22 02:10

Jeremy Brown