binding names doesn't affect the bound objects (was: print doesn't respect file inheritance?)

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Jul 26 00:07:52 EDT 2008


bukzor <workitharder at gmail.com> writes:

> I was trying to change the behaviour of print (tee all output to a
> temp file) by inheriting from file and overwriting sys.stdout

That's not what your code does, though.

> def main():
>     n = notafile('/dev/stdout', "w")

Creates a new instance of the 'notafile' class; the '=' operator then
binds that instance to the name 'n'.

>     import sys

Imports a module, and binds the module to the name 'sys'. This
includes, usually, the module attribute named by 'sys.stdout'.

>     sys.stdout = n

Re-binds the name 'sys.stdout' to the object already referenced by the
name 'n'. No objects are changed by this; only bindings of names to
objects.

>     print "Testing: 1, 2, 3..."

Doesn't rely at all on the name 'sys.stdout', so isn't affected by all
the binding of names above.


In other words, you can't change the object used by the 'print'
statement only by re-binding names (which is *all* that is done by the
'=' operator).

You can, however, specify which file 'print' should use
<URL:http://www.python.org/doc/ref/print.html>.

-- 
 \      “When I wake up in the morning, I just can't get started until |
  `\     I've had that first, piping hot pot of coffee. Oh, I've tried |
_o__)                                    other enemas...” —Emo Philips |
Ben Finney



More information about the Python-list mailing list