Python: Lifetime of module-global variables

坚强是说给别人听的谎言 提交于 2019-12-04 12:56:27

Objects that are no longer referenced are indeed garbage collected (they are deleted automatically when their reference count drops to 0).

A module global, however, will never have it's reference count drop to 0; once imported a module object (its namespace), lives in the sys.modules mapping. The namespace itself refers to your object.

In other words, your object lives on forever, until you either delete it from the module namespace, delete the module namespace itself (del sys.modules['yourmodule']) or your python script exits.

If the module containing the global is in scope from the start of your execution to the end then the globals will be to. Might be cleaner to use a class instance though.

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