Import Best Practices?

I’ve got a working streamlit app that I wanted to clean up a bit by reorganizing the code into modules and I decided to review the source code for the streamlit hello app to get a sense of best practices.

I was surprised to see that the app runs the necessary imports for each demo app inside of the corresponding function for that app. For example:

def mapping_demo():
    import streamlit as st
    import pandas as pd
    import pydeck as pdk

    def from_data_file(filename):
        url = (
            "example-data/master/hello/v1/%s" % filename)
        return pd.read_json(url)

Is that a recommended practice for Streamlit or something specific to the demo? Is it a more general practice that I’m just unaware of (as opposed to doing all imports at the top of each file)?


Hey @sterlinm, welcome to the Streamlit community!

This isn’t actually a best practice, but an off-shoot of us wanting to provide clear demo examples. If we don’t put the imports inside those functions, they don’t get displayed to the user in the code example box, which sometimes causes user confusion.

So we’re just trying to balance the educational aspect of it vs. what you would normally see in Python code.


1 Like

Thanks for the quick response! That makes sense.

1 Like