How to properly split one Python file into multiple files

I have just created my first app.py for Streamlit. However, the lines of code are growing fast, as I am creating a lot of different sections with information.

I want to split the contents of app.py into subfiles.

I tried using exec(open("./subfile.py").read()), which works, but my understanding is that this is bad practice. (NB: Iโ€™m not importing any external code in the subfiles, only creating some variables and referencing some external iframe URLs via components.html and components.iframe.

Furthermore, Streamlit doesnโ€™t detect changes in subfile.py so you arenโ€™t prompted to Rerun or Always Rerun the code upon editing it.

How should I split my project into multiple files, and can it be made to work with Always Rerun?

1 Like

Hi @GExv, welcome to the Streamlit community!

You are right, moving things to multiple files can be tricky, because Streamlit doesnโ€™t necessarily monitor every folder that might have Python code in it. The way Iโ€™d suggest breaking things up would be similar to structuring other Python code. Where possible, writing functions is a great idea, and as functions get finalized, you can move them to other files and not be worried about refreshes.

In terms of exec, yes, you almost never want to execute raw strings in any programming language unless you are 100% sure of their contents. In Python, you almost certainly shouldnโ€™t be doing it.

Is there a code repo you are willing to share that we can give you tips about?

Best,
Randy