Following on from Add umask to contextlibshutil, which is now pending its merge, this thread discusses relocating contextlib.chdir alongside umask in shutil. This may set an established location for environment-manipulating context managers, and in doing so resolves some feature-creep inside contextlib.
A preview of my suggested changes so far, including the process of gently deprecating contextlib.chdir, can be found here.
The causes which impel the separation
It is of the opinion that contextlib should consist of “tools for making and manipulating context managers”, a module primarily for base classes and agnostic decorators. It should not be a scratch pad for all stdlib context manager implementations.
chdir’s admission to contextlib was after much debate, but in retrospect there was an oversight in the scope of its behavior: chdir is not just a context manager that provides control flow within a Python script, or even just manipulates module-level attributes as redirect_std{out,err} do; it affects the execution environment of the whole process via syscalls!
chdir’s effect of temporarily changing the current working directory is done by the chdir wrapper around chdir(2) within the os module, whose only reason for import into contextlib is to provide this. A quick ctrl+f search of shutil.py gives over 200 matches for os., and it seems like a better home for chdir, next to the newly expected umask context manager, which also affects the process’s execution environment via the os.umask wrapper around umask(2). That’s one less import for contextlib!
With the addition of umask, the documentation for shutil was updated with the creation of a section titled ‘Context managers to modify process execution environments’. This is intended to set a precedent, that chdir can easily slot into. Some of the documentation for this section was salvaged and generalized from chdir too.
Deprecating contextlib.chdir
I’ve gone with
# contextlib.py
def chdir(path):
import warnings
from shutil import chdir as chdir_shutil
warnings.warn('contextlib.chdir has been relocated to shutil.chdir',
DeprecationWarning, stacklevel=2)
return chdir_shutil(path)
so far. Lazily importing shutil within the chdir function probably avoids overhead and a cyclic-dependency between shutil and contextlib. Please point out if there’s something wrong; I haven’t deprecated much before!
No timeline has been set for the deprecation.
Related possibilities for cleaning up contextlib
There have also been mentions in the previous thread that contextlib.redirect_std{out,err} may be too specific / side-effect heavy / better located in somewhere like shutil than in contextlib. Perhaps these could follow a similar process of relocation, or perhaps that’s for another thread.