D'Arcy Cain <da...@vybenetworks.com> writes: > On 2019-06-10 15:46, Alan Bawden wrote: > > D'Arcy Cain <da...@vybenetworks.com> writes: > >> with open("file","w+") as fd: > > > > That makes the window smaller, but it doesn't actually eliminate it. Look > > at the generated byte code. In both cases the call to open() is over and > > the open file is created _before_ the SETUP_WITH instruction is executed. > > Am I correct in assuming that the window is there for process interrupts > but not threads?
I believe that _either_ a signal handler invocation _or_ a thread switch might happen immediately before the SETUP_WITH instruction, so there is a window in either case. You probably do have less to worry about in the thread switch case, because eventually the thread will resume where it left off (there being no way to kill a thread). In the interrupt case it is possible that a KeyboardInterrupt will kill your thread right before the SETUP_WITH, and then the stream's __exit__ method will never be called. But you don't have much to worry about in that case either because the ONLY reference to the stream is on the top of the stack, so after the thread is unwound the stream will become garbage, and then the garbage collector will close it. But my point was that replacing: f = open(...) with f: with with open(...) as f: doesn't fully close _any_ timing windows, it's just clearer to write it that way. -- Alan Bawden -- https://mail.python.org/mailman/listinfo/python-list