classification
Title: pathlib: remove partial support for preserving accessor when modifying a path
Type: performance Stage: patch review
Components: Library (Lib) Versions: Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: barneygale
Priority: normal Keywords: patch

Created on 2020-03-22 05:15 by barneygale, last changed 2020-04-03 17:40 by barneygale.

Pull Requests
URL Status Linked Edit
PR 19342 open barneygale, 2020-04-03 17:40
Messages (1)
msg364783 - (view) Author: Barney Gale (barneygale) * Date: 2020-03-22 05:15
`pathlib.Path._init()` accepts a 'template' argument that pathlib uses - in some cases - to preserve the current accessor object when creating modified path objects. This works for `resolve()`, `absolute()` and `readlink()`, *but no other cases*!

As customizing the accessor is not something we support (yet! see https://discuss.python.org/t/make-pathlib-extensible/3428), and the majority of path methods do not call `_init()` with a 'template' argument (and so do not preserve the accessor), I suggest this internal functionality be removed. Together with bpo-39682 / gh-18846, I believe this would allow us to remove `Path._init()` entirely, which would be a small performance win and a simplification of the code.

Demo:

```
import pathlib


class CustomAccessor(pathlib._NormalAccessor):
    pass


def print_accessor(path):
    if isinstance(path._accessor, CustomAccessor):
        print("    %r: custom" % path)
    else:
        print("    %r: normal" % path)


print("Here's a path with a custom accessor:")
p = pathlib.Path("/tmp")
p._accessor = CustomAccessor()
print_accessor(p)

print("Our accessor type is retained in resolve(), absolute() and readlink():")
print_accessor(p.absolute())
print_accessor(p.resolve())
#print_accessor(p.readlink())

print("But not in any other path-creating methods!")
print_accessor(p.with_name("foo"))
print_accessor(p.with_suffix(".foo"))
print_accessor(p.relative_to("/"))
print_accessor(p / "foo")
print_accessor(p.joinpath("foo"))
print_accessor(p.parent)
print_accessor(p.parents[0])
print_accessor(list(p.iterdir())[0])
print_accessor(list(p.glob("*"))[0])
print_accessor(list(p.rglob("*"))[0])
#print_accessor(p.expanduser())
```
History
Date User Action Args
2020-04-03 17:40:35barneygalesetkeywords: + patch
stage: patch review
pull_requests: + pull_request18706
2020-03-22 05:15:29barneygalecreate