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()
wbandmyDFare in the same file asmyFunction? If not, did you import them into the same file?wbandmyDFcome from the global scope wheremyFunctionis defined, not the one where it is called. "Global" is a bit of a misnomer, in that every module has its own global scope; the only program-wide scope in Python is the built-in scope (which is effectively a read-only scope; you cannot add names to it).from module import xthat creates a new variablexin the module doing the importing, but global modifications in the imported module affectmodule.x. here's the good news: this is a good thing and the approach you were trying to take is an antipattern to begin withglobal. Use parameters and return values like every experienced programmer.