Multipage: How to import module from different directory

I am trying to build a multipage dashboard where each page uses functions written in a separate .py files. Title_page.py can read function (called ‘add_two()’) from func_1.py without any problem. However, Page2.py can’t seem to read function (called ‘multiply_two()’) from func_2.py under p2_functions folder, which is placed inside the pages folder. It throws an error saying:

ModuleNotFoundError: No module named ‘p2_functions’

I think it’s because streamlit is ignore anything other than .py files inside the pages folder, but I don’t know how then I could call modules and read functions from other .py files or from other folders.

Here’s what I have in the Page2.py:

import streamlit as st
from p2_functions.func_2 import multiply_two

st.markdown("# Page 2 ")
st.write(multiply_two(10 * 20))

Here’s the tree of the structure:

├── Title_page.py
├── func_1.py
└── pages
    ├── Page2.py
    └── p2_functions
        └── func_2.py

Hey @oleole,

I think you need to do:

from pages.p2_functions.func_2 import multiply_two

Imports in Streamlit always work relative to the directory where you run streamlit run ..., so in your case the root of your directory.

1 Like

Oops you’re right!! Thanks for your quick feedback!!

One more question. If I have multiple big dashboards for each page, I wonder if streamlit executes each page separately or execute all dashboards at the same time which in latter case would take a lot of memory and time to view just one page.

It should only execute the page you are currently viewing, not all pages at the same time / at startup. Note that some things (e.g. st.cache or st.session_state) are kept in memory among all pages, though.

1 Like

@jrieke Thanks for your clarification. What about using tabs instead of page? If I have two tabs on the same page on a multipage dashboard, would it execute both tabs at the same time? Or does streamlit only execute the tab you are currently viewing?

st.tabs currently renders the content of all tabs at the same time. There’s no way to only render the tab you are viewing. We have some ideas to add that behavior in the future but it’s low priority right now.