osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question About When Objects Are Destroyed


On 8/4/17 7:42 PM, Jon Forrest wrote:
> On 8/4/2017 4:34 PM, gst wrote:
>> 'two' is a so called constant or literal value .. (of that
>> function).
>>
>> Why not attach it, as a const value/object, to the function itself ?
>> So that a new string object has not to be created each time the
>> function is called. Because anyway strings are immutable. So what
>> would be the point to recreate such object every time the function is
>> called ?
>
> This was just an example program, not meant to do anything
> meaningful. I would think that the same object behavior would
> occur if I dynamically created an object in that function.
>
"The same object behavior" does occur: the object is freed when there
are no more references to it. But if the object is a literal in the
function, then the function keeps a reference to it. On the other hand,
if it's dynamically computed, the function has no reference to it.  That
reference can change the behavior you see.

Others have already mentioned some reasons why you are seeing the
behavior you see. Another I don't think I saw mentioned: perhaps with
ctypes you are examining memory that has been freed, but not cleared,
and in fact the object doesn't still exist.

This is the best way I know to explain a lot of these issues:
https://nedbatchelder.com/text/names1.html

You seem comfortable with C ideas and techniques. You might have to let
go of some habits and let Python do its work. :)

--Ned.