Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there stack based variables in Python?

Tags:

python

If I do this:

def foo():
     a = SomeObject()

Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen?

like image 457
Assaf Lavie Avatar asked Jun 24 '09 10:06

Assaf Lavie


People also ask

Does Python have stack variables?

When a method is called in Python, a stack frame is allocated. This stack frame will handle all the variables of the method.

Are Python variables on the stack or heap?

Memory Allocation in Python The methods/method calls and the references are stored in stack memory and all the values objects are stored in a private heap.

Do variables reside in stack memory Python?

Code (also called Text or Instructions) section of the memory stores code instructions in a form that the machine understands. The machine follows instructions in the code section. According to the instruction, the Python interpreter load functions and local variables in the Stack Memory (also called the Stack).

Are variables stored on the stack?

The stack is used for dynamic memory allocation, and local variables are stored at the top of the stack in a stack frame. A frame pointer is used to refer to local variables in the stack frame.


1 Answers

Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is immediate or not is an implementation detail, and will vary.

In CPython (the standard python implementation), refcounting is used, so the item will immediately be destroyed. There are some exceptions to this, such as when the object contains cyclical references, or when references are held to the enclosing frame (eg. an exception is raised that retains a reference to the frame's variables.)

In implmentations like Jython or IronPython however, the object won't be finalised until the garbage collector kicks in.

As such, you shouldn't rely on timely finalisation of objects, but should only assume that it will be destroyed at some point after the last reference goes. When you do need some cleanup to be done based on the lexical scope, either explicitely call a cleanup method, or look at the new with statement in python 2.6 (available in 2.5 with "from __future__ import with_statement").

like image 68
Brian Avatar answered Sep 23 '22 04:09

Brian