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
.)
Yes. The two variables refer to the same file object. Closing either closes the object itself, it doesn't matter which variable you use to refer to it.
This is no different from having two variable referring to the same list, a modification of one is visible through the other:
a = [1, 2, 3]
b = a
a.append(4)
print(b)
will print
[1, 2, 3, 4]