[Python-Dev] Possible context managers in stdlib

Guido van Rossum gvanrossum at gmail.com
Mon Jul 11 19:46:36 CEST 2005


On 7/8/05, James Y Knight <foom at fuhm.net> wrote:
> 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. A user can do it to themselves now,
> true, but by putting a context manager for it in the stdlib, you make
> it look like it'd be a local modification when it is not. I can only
> see confusion resulting from this. Users will inevitably try to use
> it like
>    with sys.redirected_stderr(f):

Which is of course a bug -- print doesn't go to stderr. Not sure if
you meant this as an illustration of a typical bug or whether you
meant sys.redirect_stdout(f).

>      print "hello"
>      print "there"
> instead of explicitly writing to f with print>> or write(). And that
> is just a terribly bad idea. It looks pretty, yes, but unless
> stdinouterr are made thread-local, it's just asking for trouble.

Boy, do you have Java (or multi-threading) on your mind. A lot of
Python programs are single-threaded, and this idiom has been promoted
by examples for many years; I see nothing wrong with it in
single-threaded code. I sure hope the world doesn't evolve to one
where most programs have to be multi-threaded to be useful!
Multi-threading is such a nightmare to program that we should really
look for paradigms that hide it completely rather than trying to raise
programmers who will write correct multi-threaded programs naturally;
the latter just ain't gonna happen.

A major use case for this, BTW, is to take *existing* Python code that
was written using print statements and wrap it in something that
captures its output. The f.write() or print>>f solutions won't work
there...

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list