The variable will exist as long as there is a reference to it. When the reference counter reaches 0, the variable is deleted. This is independent of where the reference resides - whether inside or outside a class.
Variables declared in modules are created when the code that defines them is executed. This usually occurs at the time the module is imported, unless some condition within the module prevents this.
A very common "idiom" in Python is this:
# várias definições
# ........
if __name__ == "__main__":
# executar algum código
# .....
# fim do arquivo
If you set a variable within this if
, it will only be created if this module runs directly instead of imported. The names defined above if are initialized both when the module is imported and when it is executed directly. Of course the same goes if there’s no such thing if
.
Global variables to the module, in general, exist forever, as imported modules have maintained references to them in sys.modules
. This reference prevents garbage collection, so unless your module is removed directly from there (using del
), variables defined in the module will continue to exist.