how to organize a module that requires a data file

Steven Bethard steven.bethard at gmail.com
Thu Nov 17 15:30:48 EST 2005


Larry Bates wrote:
> Personally I would do this as a class and pass a path to where
> the file is stored as an argument to instantiate it (maybe try
> to help user if they don't pass it).  Something like:
> 
> class morph:
>     def __init__(self, pathtodictionary=None):
>         if pathtodictionary is None:
>             # Insert code here to see if it is in the current
>             # directory and/or look in other directories.
>         try:  self.fp=open(pathtodictionary, 'r')
> 	except:
>             print "unable to locate dictionary at: %s" % pathtodictionary
> 	else:
>             # Insert code here to load data from .txt file
>         fp.close()
>         return
> 
>     def get_stem(self, arg1, arg2):
>         # Code for get_stem method

Actually, this is basically what I have right now.  It bothers me a 
little because you can get two instances of "morph", with two separate 
dictionaries loaded.  Since they're all loading the same file, it 
doesn't seem like there should be multiple instances.  I know I could 
use a singleton pattern, but aren't modules basically the singletons of 
Python?

> The other way I've done this is to have a .INI file that always lives
> in the same directory as the class with an entry in it that points me
> to where the .txt file lives.

That's a thought.  Thanks.

Steve



More information about the Python-list mailing list