Lifetime of a local reference
Marko Rauhamaa
marko at pacujo.net
Wed Feb 27 10:41:45 EST 2019
Rhodri James <rhodri at kynesim.co.uk>:
> On 27/02/2019 06:56, Marko Rauhamaa wrote:
>> Then there's the question of a sufficient way to prevent premature
>> garbage collection:
>>
>> def fun():
>> f = open("lock")
>> flock.flock(f, fcntl.LOCK_EX)
>> do_stuff()
>> f.close()
>> sys.exit(0)
>>
>> def fun():
>> f = open("lock")
>> flock.flock(f, fcntl.LOCK_EX)
>> do_stuff()
>> f.close
>> sys.exit(0)
>>
>> def fun():
>> f = open("lock")
>> flock.flock(f, fcntl.LOCK_EX)
>> do_stuff()
>> f
>> sys.exit(0)
>>
>> def fun():
>> f = open("lock")
>> flock.flock(f, fcntl.LOCK_EX)
>> do_stuff()
>> sys.exit(0)
>
> I would go with:
>
> def fun():
> with open("lock") as f:
> flock.flock(f, fcntl.LOCK_EX)
> do_stuff()
> sys.exit(0)
>
> The description of the with statement does explicitly say that the
> context manager's __exit__() method won't be called until the suite
> has been executed, so the reference to the open file must exist for at
> least that long.
Yeah, but the *true* answer, of course, is:
def fun():
f = os.open("lock", os.O_RDONLY)
flock.flock(f, fcntl.LOCK_EX)
do_stuff()
sys.exit(0)
Collect that!
;-)
Marko
More information about the Python-list
mailing list