Are function and class definitions being rerun every time the app is rerun?

I define some functions and classes at the start of my script, they are somewhat expensive to define. Are these function and class defines being rerun every time i rerun the app? What i see from all the sources online is that @st.cache only caches the running of the functions, not the defining of the functions. Is there any way to have my script only define the functions the first time the script is ran?

P.S. do imports have the same problems too?

Hi @XTP, welcome to the Streamlit community!

Do you have a repo that demonstrates this behavior that you can share? In general, having several references to a module import only happens a single time in Python, but I might be misunderstanding the question.

Best,
Randy

okay that answers one of my questions, my other question is whether or not a function define happens only a single time or every time my app is rerun?

I’m not an expert in Python’s internals, but I do know that Python can save the bytecode between runs. So if it can determine that the code hasn’t changed, I presume that the bytecode doesn’t get regenerated(?).

If that intuition is true, then it’s probably best to have complex code defined outside of the actual Streamlit app code and then imported.