Here is a scenario:
- I get a list of sentences from a database (MySQL).
- I read a file into a dictionary.
- Process each sentence based on the dictionary.
My initial (horrible) approach was:
- Had two modules.
ModuleA
got the sentences from database and calledfunctionB
per sentence.FunctionB
which is inModuleB
populates the dictionary from file. Each time. Then it processes the sentence.
This was done so because initially I was testing ModuleB
separately. Later, when FunctionB
was being called repeatedly I had to fix this. My solution was to move the population of dictionary from file to a separate function and set a global dictionary. Code goes like:
ModuleA
import ModuleB
def main():
sentences = getSentencesFromDB()
for (sentence in sentences):
functionB(sentence)
ModuleB
dictionary = makeDictionaryFromFile()
def functionB(sentence):
for word in sentence.split():
#process sentence using dictionary
Now my questions are:
- Is this the correct solution to my problem? That is, does this ensure file is read only once?
- Is there a better way to do this (maybe without using global).
- When is the
dictionary
populated? On first call tofunctionB
? Or when importingModuleB
?