Skip to content

Add ModificationContext ABC to contextlib. #128574

@jb2170

Description

@jb2170

Feature or enhancement

Proposal:

We add an ABC ModificationContext to contextlib:

ModificationContext specializes the functionality of AbstractContextManager, for context managers designed to change the value of a state or attribute on entry, and revert it on exit. We have noticed that this style is used by many existing and proposed context managers.

The following classes already present in contextlib are to be refactored to inherit from ModificationContext (with no compatibility issues)

  • contextlib._RedirectStream, parent of redirect_stdout and redirect_stderr
  • contextlib.chdir

After this addition, the following issues are rebased, so that their additions inherit from ModificationContext:

  • gh-128432: Add shutil.umask
  • TBC: Add shutil.seteuid and shutil.setegid
  • gh-128432: Move contextlib.chdir to shutil.chdir

This addition makes those first two PRs trivial, and contextlib.chdir is refactored whether it is moved to shutil or not.

Has this already been discussed elsewhere?

I have already discussed this feature proposal on Discourse

Links to previous discussion of this feature:

Thread started by @ncoghlan

https://discuss.python.org/t/adding-a-contextlib-modificationcontext-base-class/76322/2

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions