I have a file main_file.py that creates a global variable file_obj by opening a text file and imports a module imported_module.py which has functions that write to this file and therefore also has a global variable file_obj which I set equal to file_obj in main_file.py:
main_file.py
import imported_module as im
file_obj = open('text_file.txt', mode='w')
im.file_obj = file_obj
def main():
a = 5
b = 7
im.add_func(a, b)
im.multiply_func(a, b)
return
def add_func(x, y):
z = x + y
file_obj.write(str(z) + '\n')
return
main()
file_obj.close()
imported_module.py
file_obj = None
def multiply_func(x, y):
z = x * y
file_obj.write(str(z) + '\n')
return
If I close file_obj in main_file.py as above, does this also nicely close file_obj in imported_module.py?
(In the MRE above, I could add im.file_obj.close() to main_file.py just to be sure. However, a generalization of this explicit approach does not appear possible if imported_module.py imports a second module imported_module0.py which also has a global variable file_obj and sets this variable to its own copy of file_obj with a command like im0.file_obj = file_obj.)
im.file_obj = file_objisn't a copy.im.file_objis just a name for the same object. But why not use theloggingmodule instead of reinventing the wheel?loggingin the past with good success, but in this application I'm seeking to write to a text file without the level and module information thatloggingautomatically adds to each line. Apparently, this can be removed, but with a multi-step customization involving alogging.Formatterobject, etc. Still, I agree thatloggingis great for many applications.