"__main__" executing with every page render - re-initializing all my class objects

Summary

From when I start my Streamlit app to any time I trigger a re-render, it repeatedly executes my “main” method, which rebuilds my entire application every time. As a consequence, I can’t keep anything in memory between renderings.

If I print whenever my objects are initialized, you can see it happening:

/Users/devin.bost/opt/miniconda3/envs/graphing/bin/python /Users/devin.bost/opt/miniconda3/envs/graphing/bin/streamlit run main.py 

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8502
  Network URL: http://192.168.1.70:8502

running __name__ == "__main__"
running __init__ in Main
running __name__ == "__main__"
running __init__ in Main
ran buildUI
ran startChatbot
ran __init__ on Chatbot
running __init__ on UserInterface
Running render
ran buildUI
ran startChatbot
ran __init__ on Chatbot
running __init__ on UserInterface
Running render
running __name__ == "__main__"
running __init__ in Main
ran buildUI
ran startChatbot
ran __init__ on Chatbot
running __init__ on UserInterface
Running render

Steps to reproduce

Here is how I’m starting Streamlit:

My main method (in main.py) is pretty simple:

if __name__ == "__main__":
    print('running __name__ == "__main__"')
    main = Main()
    main.buildUI()

I suppose I could have it instantiate a class instead of Main() since it’s currently a bit self-referencing, but I’m not seeing how that would change this behavior.

The other two methods in that call chain are pretty straightforward:

    def startChatbot(self):
        print("ran startChatbot")
        if self.chatbot is None:
            self.chatbot = Chatbot(self.dataAccess)

    def buildUI(self):
        print("ran buildUI")
        self.startChatbot()
        ui = UserInterface(self.dataAccess, self.chatbot, self.crawler)
        ui.render()

I added the if self.chatbot is None check when I was trying to figure out why my chatbot was getting wiped out, but since Main() keeps getting reconstructed, it’s doing me no good.

Streamlit, version 1.27.0
Python 3.11.5
conda 22.9.0
Macbook Pro (M1)
Chrome version 117.0.5938.149 (Official Build) (arm64)

Code is here: GitHub - devinbost/moonshot: Use of AstraDB with a web crawler to extract code and execute with LangChain and an LLM

Hi @Devin_Bost

According to the default app behavior, whenever any widgets is altered, this triggers an app refresh and everything starts fresh. In order to retain memory, you can do that by using Session state which will allow you to retain any widget state as well as for storing variable values.

More info and examples below:

Hope this helps!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.