Does Python create everything from a heap?

in c / c ++, you have variables on the stack when you create a local variable inside a function.

http://effbot.org/zone/call-by-object.htm

CLUs exist regardless of the activation of a procedure. Space for objects stands out from the field of dynamic storage /.../In theory, all objects continue to exist forever. In practice, the space used by an object can be restored when the isno object is more accessible to any CLU program.

Does this mean that objects in python are created from the heap (as in malloc in c / C ++)? and objects are freed when there is no name associated with them? (e.g. smart pointers)?

Example:

def foo(a): result = [] result.append(a) return result foo("hello") myList = foo("bye") 

So, the first result ([]) was created on the heap and received the release because there is no name associated with it?

+7
source share
3 answers

Yes, all Python objects live on the heap (at least on CPython.) They are counted by reference: they are de-allocated when the last reference to the object disappears. (CPython also has a garbage collector to interrupt loops.)

In CPython, your first list disappears as soon as the function returns, since you did not bind the return value to the name, and the reference count fell to zero. In another implementation, an object can live longer until the garbage collector starts.

Some objects (for example, open files) have attached resources that are automatically released when the object is released, but because of the above, it is not recommended to rely on this. Resources should be closed explicitly when you are done with them.

+12
source

Yes, all values ​​in CPython are allocated on the heap and reference the count in order to know when to free them. Unlike C, in most cases there is no way to find out if a value will survive its function, so the only safe thing is heap-highlight everything.

Of course, you could do some analysis and determine that certain values ​​are never passed to functions and therefore cannot escape, but limited use in Python and additional overhead would probably not be worth it.

+5
source

As a complement to the other answers, here is one way to track when garbage collection occurs using the special __del__ method:

 class Test(object): def __init__(self, name): self.name = name def __del__(self): print "deleting {0}".format(self.name) print "discarded instance creation" Test("hello") print "saved instance creation" myList = Test("bye") print "program done" 

Output:

  discarded instance creation
 deleting hello
 saved instance creation
 program done
 deleting bye

See gc module for more details.

+4
source

All Articles