New submission from Antony Lee <[email protected]>:
Many functions which take a path-like object typically also accept strings
(sorry, no hard numbers here). This means that if the function plans to call
Path methods on the object, it needs to first call Path() on the arguments to
convert them, well, to Paths. This adds an unnecessary cost in the case where
the argument is *already* a Path object (which should become more and more
common as the use of pathlib spreads), as Path instantiation is not exactly
cheap (it's on the order of microseconds).
Instead, given that Paths are immutable, `Path(path)` could just return the
exact same path instance, completely bypassing instance creation (after
checking that the argument's type exactly matches whatever we need and is not,
say, PureWindowsPath when we want to instantiate a PosixPath, etc.). Note that
there is prior art for doing so in CPython: creating a frozenset from another
frozenset just returns the same instance:
```
In [1]: s = frozenset({1}); id(s) == id(frozenset(s)) == id(s.copy())
Out[1]: True
```
----------
components: Library (Lib)
messages: 362874
nosy: Antony.Lee
priority: normal
severity: normal
status: open
title: Optimize construction of Path from other Paths by just returning the
same object?
versions: Python 3.9
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue39783>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com