Avoiding global variables and loading models at startup in Python

Viewed 1903

I realize that using global variables isn't a good coding practice. I need to load a machine learning model at startup, so that I don't need to process it at each request. I have Flask to handle the requests. However I am unable to understand what is a good practice to initialize a variable at startup in Python. In Java I guess my approach would be to use a class with a static variable in the following way:

Class A{
   private ClassB classB;
   A() {
      //Load some file into memory
      classB = new ClassB();
      classB.x = //set from file
   }

   public static getClassB() {
    return classB;
   }
}


Is this something which is a good practice to follow in Python as well? I could then probably do something like

@app.route('/', methods=['GET'])
  def main():
     b = getClassB() ; //this time it shouldn't load
     score = b.predict()
     return score

 if __name__ == 'app':
    try:
        getClassB() //this will load once at startup
    except Exception,e :
        print 'some error'
1 Answers
Related