1

I'm trying to make a data frame object global and i'm running into trouble and I'm not sure why. I have this across 2 files: main.py and helperFunction.py

it comes down to this format helperFunction.py:

import pandas as pd
def createGlobalVars(file_path):
 global my_df
 my_df = pd.read_csv(file_path)
 print(my_df.head()

main.py

import helperFunction

def main():
 helperFunction.createGlobalVars('the_file.csv')
 print(my_df.head())
if __name__=='__main__':
 main()

the helper function print is correctly working:

    data
0   'my data'
1   'my data'
2   'my data'
3   'my data'
4   'my data'

but the main print is giving me my_df is not defined

This violates by what I understand about global variables so I must be missing something.

inzikind
  • 31
  • 5
  • does this answer your query ? [SO](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – mrrobot.viewsource Feb 24 '23 at 14:40
  • following that and adding `my_df=None` to the top of the `helperFunction.py` file and changing the import in main to `from helperFunction.py` import * and the call to `createGlobalVars('the_file.csv')` now returns `None Type has no method head()` in the main – inzikind Feb 24 '23 at 14:42

1 Answers1

0

If you mutate your global variable instead of assigning to it, things will work as expected:

# helperFunction.py

import pandas as pd

my_df = []

def createGlobalVars(file_path):
    global my_df
    my_df.append(pd.read_csv(file_path))
# main.py

from temp2 import *

def main():
    createGlobalVars('the_file.csv')
    print(my_df[0].head())


if __name__=='__main__':
    main()

With the following the_file.csv:

a,b
1,2

Running python main.py outputs:

   a  b
0  1  2
Laurent
  • 12,287
  • 7
  • 21
  • 37