Question About When Objects Are Destroyed

Terry Reedy tjreedy at udel.edu
Fri Aug 4 22:36:00 EDT 2017


On 8/4/2017 7:11 PM, Jon Forrest wrote:
> Consider the following Python shell session (Python 3.6.2, Win64):
> 
>  >>> def givemetwo():
> ...         x = 'two'
> ...         print(id(x))
> ...
>  >>> givemetwo()
> 1578505988392
> 
> So far fine. My understanding of object existence made me
> think that the object referred to by x would be deleted when
> the givemetwo() function returned, like a local variable in C.

Python does not specifically delete objects.  It deletes references to 
objects, such as an association between a name and an object, or between 
a key and an object, or between a sequence index and an object.  When a 
function returns, associations between local names and object are 
deleted. Python on a machine does not necessarily spend time 'cleaning' 
memory by overwriting it with 0s.

> However, this isn't true, as shown by the following in the same
> session:
> 
>  >>> import ctypes

Most everything you see in the manuals (and on this list) has a little * 
after it.

* unless one imports and uses ctypes (or 3rd party modules).

For instance, 'Python code, even if buggy, should not crash the 
interpreter'* and 'If you find such code, it is a bug'*, 'Please open an 
issue on the tracker'*.  If you use ctypes, please don't.

>  >>> print (ctypes.cast(1578505988392, ctypes.py_object).value)
> two
> 
> This shows that the object still exists, which was a surprise.
> Will this object ever be deleted? 

What do you mean deleted? At this point, you are not looking at a normal 
Python object, as such, but rather the contents of a segment of machine 
memory at a particular address, extracted into a ctypes.py_object 
object.  I don't think you want that chunk of memory destroyed.

The only public attribute of the ctypes.py_object object is .value.  It 
has a few undocumented private attributes, such as ._b_needsfree_ which, 
when I tried it, is 1.

-- 
Terry Jan Reedy




More information about the Python-list mailing list