What is the best practice for passing variable to entire module for use by all functions in package (in Python)?
I am learning Python. I have created a .py file for reading and writing to an excel spreadsheet. It has several functions, for writing, reading, saving, etc. In a separate .py file, I want to call these functions. I would like to pass the variable of the filepath into this package. Is there a better way than individually passing the variable to each excel function? Can I pass the filepath variable as a whole to be share by all excel functions?
In the file with the functions create a module level variable that the functions use. In the second file, after importing, assign a new value to the variable in the first file.
a.py
var1 = 'one'
def f():
print(var1)
def g():
print(var1)
b.py
import a
a.var1 = 'two'
a.f()
a.g()
Using parameters with default arguments in the functions will not work; the parameter's value is bound when the function is made (when the module is imported) and subsequently reassigning var1
will not affect z
in the functions.
this does NOT work
var1 = 'one'
def f(z=var1):
print(z)
def g(z=var1):
print(z)