开发者

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

I have a custom logging class for my Python script with a flu开发者_JAVA技巧sh() 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜