4

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'
user1692342
  • 5,007
  • 11
  • 69
  • 128

1 Answers1

2

It would be difficult to do this without some sort of global - unless you want to load the model on a per-request basis which obviously is not performant.

flask.g is really a per-request context.

Just set it up as a variable in your init file or your main file. Ala:

app = Flask(__name__)
learning_model = load_learning_model()


@app.route('/', methods=['GET'])
def home():
    #here you can use the learning model however you like

Learning model can be an instance of a class or some other type.

Callam Delaney
  • 641
  • 3
  • 15