1

I have a custom logging class for my Python script with a flush() method which print()s the contents of a list.

I would like to include flush() in the special __del__() method in case the program ends without the log being flushed. However a note in the documentation states:

[...] when del() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the del() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down).

Would anyone recommend a different way of doing this, and if so, why?

2
  • Where are you printing to? But generally, relying on finalizers is a very bad idea (largely because of the countless pitfalls, such as nondeterminstic order, nondeterministic time of finalization in cycles, the possibility that cycles with finalizers aren't broken at all, etc). Even if your design "requires" it, chances are it's the design that's broken, not __del__. Commented Oct 4, 2011 at 17:50
  • os.print() - it's a back up though. The idea is to flush() before the program exits. I'm just wondering if it's appropriate to include a guard against abnormal program termination in the class. It would likely aid in debugging if it worked. Commented Oct 4, 2011 at 18:23

1 Answer 1

1

You might want to look into making this logger a context manager. That still will not flush in the case of abnormal termination, but few things will. But __del__ might not be called on objects even in normal termination.

Loggers might be one of the things that doesn't fit well when using the with statement, as they are quite global, so it's not sure context manager is a good fit.

Sign up to request clarification or add additional context in comments.

1 Comment

In the absence of a direct answer, do you know of any resources (printed or electronic) which explain the exception handling process of the Python interpreter(s)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.