[Python-ideas] Add a `dir_fd` parameter to `os.truncate`?
Sebastian M. Ernst
ernst at pleiszenburg.de
Fri Apr 19 15:49:54 EDT 2019
Hi everyone,
many methods in `os` have a `dir_fd` parameter, for instance `unlink` [1]:
```python
os.unlink(path, *, dir_fd=None)
```
The `dir_fd` parameter [2] allows it to describe paths relative to
directory descriptors. Otherwise, relative paths are relative to the
current working directory.
The implementation of `truncate` in `os` does not have this parameter [3]:
```python
os.truncate(path, length)
```
On POSIX-like systems for instance, the `os` module actually imports [4]
this function from the `posix module`. There, one can see that it [5]
just calls the `truncate` system call [6].
This kind of implicitly explains why there is no `dir_fd` parameter:
There is no such thing like a `truncateat` system call, which would be
required for handling the `dir_fd` parameter [7, 8].
However, it is possible to work around this limitation:
```python
def truncate(path, length, dir_fd = None):
if dir_fd is None:
return os.truncate(path, length)
else:
fd = os.open(path, flags = os.O_WRONLY, dir_fd = dir_fd)
ret = os.ftruncate(fd, length)
os.close(fd)
return ret
```
Why not add a convenience function or wrapper like above to the `os`
module, which closes this gap and is more consistent with other methods?
Best regards,
Sebastian
[1] https://docs.python.org/3/library/os.html#os.unlink
[2] https://docs.python.org/3/library/os.html#dir-fd
[3] https://docs.python.org/3/library/os.html#os.truncate
[4] https://github.com/python/cpython/blob/3.7/Lib/os.py#L135
[5] https://github.com/python/cpython/blob/3.7/Modules/posixmodule.c#L9042
[6] https://github.com/python/cpython/blob/3.7/Modules/posixmodule.c#L9079
[7] https://stackoverflow.com/q/52871892/1672565
[8] https://stackoverflow.com/q/55765181/1672565
More information about the Python-ideas
mailing list