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?

Samuel Harmer
  • 4,264
  • 5
  • 33
  • 67
  • 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__`. –  Oct 04 '11 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. – Samuel Harmer Oct 04 '11 at 18:23

1 Answers1

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.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
  • 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)? – Samuel Harmer Oct 06 '11 at 14:12