Lifetime of a local reference

Thomas Jollans tjol at tjol.eu
Wed Feb 27 10:55:51 EST 2019


On 27/02/2019 16.41, Marko Rauhamaa wrote:
> Rhodri James <rhodri at kynesim.co.uk>:
>> 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!

No problemo!

try:
    fun()
except SystemExit:
    print("Oh no you don't!")

Collect this:

def fun():
    f = os.open("lock", os.O_RDONLY)
    flock.flock(f, fcntl.LOCK_EX)
    do_stuff()
    os.kill(os.getpid(), 9)


;-)


⸺ Thomas



More information about the Python-list mailing list