What is the lifetime of a variable in the method, class and module?

Asked

Viewed 202 times

1

I know that a variable declared in a method lasts for as long as the scope of the method. How python has the concept of class variables, until when lasts a variable declared in the class? And a variable declared loose in a module, when it "is born" and when it "dies"?

1 answer

0


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.