The variable will exist as long as there is a reference to it. As soon as the reference counter reaches 0, the variable is cleared. This is independent of where the reference resides inside or outside a class.
Variables declared in modules are created at the time the code that defines them is executed. This usually occurs at the time the module is imported, unless some condition within the module prevents it.
A fairly 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 that module runs directly instead of imported. The names defined above if are initialized both when the module is imported and when it is run directly. Of course the same is true if there is no such thing as if
.
Global variables for the module generally exist forever, since imported modules have references to them in sys.modules
. This reference prevents garbage collection, so unless your module is removed directly from it (using del
), variables defined in the module will continue to exist.