[Python-ideas] `to_file()` method for strings

Chris Angelico rosuav at gmail.com
Wed Mar 30 00:40:44 EDT 2016


On Wed, Mar 30, 2016 at 3:33 PM, Chris Barker - NOAA Federal
<chris.barker at noaa.gov> wrote:
>>> In the case of temporary objects that are never referred to outside a single
>>> line of code -- delete it right away.
>>
>> The problem is that there's no way to be sure. For instance, compare
>> these lines of code:
>>
>> from threading import Thread
>>
>> open("marker").write("Ha")
>> Thread(target=threadfunc).start()
>>
>> One of them has finished with the object completely. The other most
>> certainly has not.
>
> Interesting -- now I'm curious -- how does cPython know that the
> reference count of that Thread object needs to be increased So it
> won't be deleted? Does the start() method call incref() on itself?

There'll be another reference somewhere. Presumably a new stack is
allocated or something, and that's what keeps a reference. It doesn't
matter _what_ keeps the ref; all that matters is that there is one,
and that the code line itself doesn't show that. Hence you need to
explicitly say "open this, and close it when you're done".

ChrisA


More information about the Python-ideas mailing list