Python - how to save a data frame (or variable) for use and manipulation in a different module (file) without global variables

Viewed 22

I have a project with a bunch of python files (modules) that do different stuff. I keep those files in a folder called "modules". One thing I do in the project is to create a pandas data frame from an excel-file. I then read and/or modify this df in the modules.

What I do so far is to write the df in a global variable in a separate file:

-> modules/global_variables.py

import pandas as pd

df: pd.DataFrame = None
(...some other global variables...)


---------------------------

-> excel.py:

import pandas as pd
import modules.global_variables as gv

def import_xl(file) -> None:

    df = pd.read_excel("path/file.xlsx")
    (...some initial cleaning of the df...)

    gv.df = df.copy()

Now I have the data frame saved as a global variable and can access it from any other module by importing the global variables file without having to import the excel-file again (which takes a lot of time). I do the same for other variables (dicts, lists, etc.) that I need in various modules.

I read this is a bad way to do it because it uses global variables. I however don't understand how to do this without them...

Can you help?

0 Answers
Related