Is object.__del__(self) the most appropriate place to flush a logging class?

一个人想着一个人 提交于 2019-12-11 06:25:14

问题


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?


回答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.



来源:https://stackoverflow.com/questions/7651932/is-object-del-self-the-most-appropriate-place-to-flush-a-logging-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!