New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Path.unlink should have a missing_ok parameter #77304
Comments
Similarly to how several pathlib file creation functions have an "exists_ok" parameter, we should introduce "missing_ok" that makes removal functions not raise an exception when a file or directory is already absent. IMHO, this should cover Path.unlink and Path.rmdir. Note, Path.resolve() has a "strict" parameter since 3.6 that does the same thing. Naming this of this new parameter tries to be consistent with the "exists_ok" parameter as that is more explicit about what it does (as opposed to "strict"). |
It can be written as
If you want to save few lines of code, you can use contextlib.suppress(). with suppress(FileNotFoundError): path.inlink() I suggest to close this issue. It is better to keep the API simple and orthogonal. Adding an option in Path.unlink() will require adding this support of this option in third-part implementations of Path. In general, adding a single boolean parameter is not considered a good practice in Python. A "strict" parameter in Path.resolve() does the different thing. In both cases Path.resolve() returns a value, and you can't implement strict=False by catching exception externally. |
This would be a shortcut in the common case that you simply want an idempotent "make sure this file/symlink is gone" operation. There are already boolean options to enable idempotent behaviour in several pathlib implementations, such as mkdir(exist_ok=True) and touch(exist_ok=True). write_bytes() and write_text() are also idempotent. unlink() aligns well with this. Because this operation doesn't exist, developers are tempted to write if path.exists():
path.unlink() which both has a TOCTTOU bug and doesn't correctly handle symlinks. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: