From 5a4b0b03d62b57d4c2b74269a7a74306f8a8e023 Mon Sep 17 00:00:00 2001 From: JustAnotherArchivist Date: Mon, 3 Jan 2022 23:59:56 +0000 Subject: [PATCH] Fix file object treatment in docs Without using the file object as a context manager, it's highly likely that the file won't be closed until after the lock is released. Thus two processes could attempt to access the file at the same time despite the lock. --- docs/index.rst | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/index.rst b/docs/index.rst index bc95510..91afc0d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -10,7 +10,8 @@ simple way of inter-process communication: lock = FileLock("high_ground.txt.lock") with lock: - open("high_ground.txt", "a").write("You were the chosen one.") + with open("high_ground.txt", "a") as f: + f.write("You were the chosen one.") **Don't use** a :class:`FileLock ` to lock the file you want to write to, instead create a separate ``.lock`` file as shown above. @@ -59,11 +60,13 @@ locks: .. code-block:: python with lock: - open(file_path, "a").write("Hello there!") + with open(file_path, "a") as f: + f.write("Hello there!") lock.acquire() try: - open(file_path, "a").write("General Kenobi!") + with open(file_path, "a") as f: + f.write("General Kenobi!") finally: lock.release() @@ -74,7 +77,8 @@ acquired within ``timeout`` seconds, a :class:`Timeout ` excep try: with lock.acquire(timeout=10): - open(file_path, "a").write("I have a bad feeling about this.") + with open(file_path, "a") as f: + f.write("I have a bad feeling about this.") except Timeout: print("Another instance of this application currently holds the lock.") @@ -84,12 +88,14 @@ The lock objects are recursive locks, which means that once acquired, they will def cite1(): with lock: - open(file_path, "a").write("I hate it when he does that.") + with open(file_path, "a") as f: + f.write("I hate it when he does that.") def cite2(): with lock: - open(file_path, "a").write("You don't want to sell me death sticks.") + with open(file_path, "a") as f: + f.write("You don't want to sell me death sticks.") # The lock is acquired here.