[New-bugs-announce] [issue39783] Optimize construction of Path from other Paths by just returning the same object?

Antony Lee report at bugs.python.org
Fri Feb 28 06:36:37 EST 2020


New submission from Antony Lee <anntzer.lee at gmail.com>:

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 <report at bugs.python.org>
<https://bugs.python.org/issue39783>
_______________________________________


More information about the New-bugs-announce mailing list