'Using global variables when importing functions

import openpyxl as pyxl
from functions import myFunction

wb = pyxl.load_workbook("data.xlsx")
myDF = pd.DataFrame(columns=cols, index=rows)

The code below works, when I pass in the workbook and dataframe

myFunction(wb, myDF)

but if it doesn't work if I declare global variables within the import function, getting an error of 'NameError: name 'wb' is not defined.' so I don't believe it's recognising the global variable from the main script. Any ideas of what I'm doing wrong?

#from the imported code
myFunction():
  global wb
  global myDF
  ws = wb['Sheet1']

#run from the main script
myFunction()


Solution 1:[1]

Globals in Python are global to a module, not across all modules. as explained in this answer Visibility of global variables in imported modules

So you have to put this code inside your functions in order to work:

import openpyxl as pyxl
import pandas as pd

wb = pyxl.load_workbook("data.xlsx")
cols=['A','B'] #for example purposes
rows=range(1,10) #for example purposes
myDF = pd.DataFrame(columns=cols, index=rows)

def myFunction(): 
    global wb
    global myDF
    ws = wb['Sheet1']
    

And in your main module

from functions import myFunction

myFunction()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1