[Python-Dev] Possible context managers in stdlib

Michael Chermside mcherm at mcherm.com
Fri Jul 8 23:39:22 CEST 2005


James Y Knight writes:
> It is a really bad idea to codify the practice of modifying non-
> threadlocal global state like sys.std[in|out|err] and current
> directory with a context manager.

Barry Warsaw responds:
> Thinking about the types of code I write over and over again, I think I
> disagree (slightly) with James about the global state thing.  While I
> agree that 'with redirected_stdio' isn't too useful in the face of
> print>>, I very often have to write try/finally protections around
> temporary settings of the cwd, the umask, and other global process
> values.  I'd love to see cm's for those constructs in the stdlib.

I agree with Barry. Not only should they be in the stdlib, but they
should have very clear warnings in their docstrings and other documentation
that state that they are ONLY safe to use in single-threaded programs.

This achieves two things: it makes them available to those who need
them (not everyone uses threads!), and it rather forcefully makes the
point that it's NOT usually a good idea to modify global state info in
a context manager because doing so is not generally threadsafe.

-- Michael Chermside



More information about the Python-Dev mailing list