1

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.)

3
  • 1
    Yes, it will close the object. im.file_obj = file_obj isn't a copy. im.file_obj is just a name for the same object. But why not use the logging module instead of reinventing the wheel? Commented May 9 at 23:28
  • Thanks @Mark. I have used logging in the past with good success, but in this application I'm seeking to write to a text file without the level and module information that logging automatically adds to each line. Apparently, this can be removed, but with a multi-step customization involving a logging.Formatter object, etc. Still, I agree that logging is great for many applications. Commented May 10 at 0:12
  • 1
    Then, instead of setting a global variable in each module that uses it, create a module that has methods to open, write, and close the log file and import that in each module. That will solve your "generalization" issue mentioned. Commented May 10 at 0:39

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.