
Sept. 16, 2021
3:07 a.m.
On Wed, Sep 15, 2021 at 12:02:04PM -0700, Guido van Rossum wrote:
To make chdir() return a context manager *and* keep it working without calling `__enter__`, it would have to call `getcwd()`, which I've heard is expensive.
So I don't think that would work, alas.
How expensive would it have to be to rule it out? Calling os.getcwd() is about 80% as costly as chdir on my machine so it is clearly not free. [steve ~]$ python3.9 -m timeit -s "import os" "os.getcwd()" 500000 loops, best of 5: 687 nsec per loop [steve ~]$ python3.9 -m timeit -s "import os" "os.chdir('.')" 500000 loops, best of 5: 842 nsec per loop But I don't think that chdir is likely to be the bottleneck in many scripts. -- Steve