Does it make sense to cache package imports?

Since streamlit reruns the app with each user interaction, are python packages being reimported every time as well?

If so, I was wondering if it makes sense to cache package imports in your streamlit app to avoid unnecessary repetitive imports. Or am I missing some fundamental underlying detail of how streamlit operates? Or are there any best practices with regards to this?

Thanks for your question. So, Python has sys.modules where all the imported modules are cached automatically so there’s no need to cache them.

This is how it typically works:

  • Python checks if a module already exists in sys.modules where imports are stored in a dictionary format. If the module exists, Python uses it and skips the import process.
  • If it doesn’t exist, Python installs it and also stores it in sys.modules.

You can read more here.

1 Like

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