json.load(open(file_path))
relies on the GC to close the file. That's not a good idea: If someone doesn't use CPython the garbage collector might not be using refcounting (which collects unreferenced objects immediately) but e.g. collect garbage only after some time.
Since file handles are closed when the associated object is garbage collected or closed explicitly (.close()
or .__exit__()
from a context manager) the file will remain open until the GC kicks in.
Using with
ensures the file is closed as soon as the block is left - even if an exception happens inside that block, so it should always be preferred for any real application.