Skip to content

Demo usage in the documentation is uncommon and misleading #313

@youkaichao

Description

@youkaichao

Thank you for the great library! It is used by over 408K github repos, and is widely influential.

I want to discuss about the demo usage in the documentation:

from filelock import Timeout, FileLock

file_path = "high_ground.txt"
lock_path = "high_ground.txt.lock"

lock = FileLock(lock_path, timeout=1)
with lock:
    with open(file_path, "a") as f:
        f.write("Hello there!")

This usage is quite uncommon and misleading. Typically, with filelock, we want the write operation to be executed by one process, and all the process just read the content, to reach the effect of broadcasting.

However, in the above example, the file is written $n$ times. And if we want to read the content after the with lock: region, the content in the file is unpredictable.

Maybe we should change to this:

import os
from filelock import Timeout, FileLock

file_path = "high_ground.txt"
lock_path = "high_ground.txt.lock"

lock = FileLock(lock_path)

with lock:
    if not os.path.exists(file_path):
        with open(file_path, "w") as f:
            f.write("Hello there!")

content = open(file_path).read()
print(content)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions