Changing default output object for

Graham Dumpleton Graham.Dumpleton at
Thu Jun 28 07:19:06 CEST 2007

I am sure someone has probably thought of this and there are good
reasons why it is a bad idea or not possible, but, is there any
technical reason why one couldn't somehow replace PRINT_ITEM byte
code, with combination of byte codes which inserted in a reference to
a file like object and then invoked PRINT_ITEM_TO byte code instead.

In other words, the aim is allow users code to use 'print' but change
where the output goes when no target file is provided.

I do know that one can replace sys.stdout with another file object in
the simple case, or in the more complicated case with a file like
object that determines where to redirect output based on the calling
thread identity or some over criteria, but wanted to see if some one
could do something without modifying sys.stdout.

One particular example where I thought this might be interesting is to
allow in a web templating system where Python code blocks can be
embedded in markup, the use of the 'print' statement without a user
having to know that they really need to direct output to a special
file object, eg. 'print >> response'. Procedure might thus be to load
Python code snippets and compile to byte code. Fixup byte code to
change PRINT_ITEM to PRINT_ITEM_TO with other byte codes added to
insert appropriate reference to file like object being supplied
through data only passed to code object when executed. Cache code for
ongoing use. Invoke code object as required, supplying reference to
file object for output.

In some template systems such as in they replace sys.stdout
with a magic object which based on the identity of the thread making
calls to the methods of sys.stdout, will redirect the output back to a
registered response object, but instead of doing it this way, could
byte code manipulation provide another way.

Anyway, just curious as to whether it would be possible or not and if
someone has an example of doing it using byteplay or similar would
love to see what is required.


More information about the Python-list mailing list