sys.stdout.write()

Alex Martelli aleaxit at yahoo.com
Tue Dec 19 18:01:36 CET 2000


"Daniel Klein" <DanielK at aracnet.com> wrote in message
news:r3M%5.159$LU6.61501 at typhoon.aracnet.com...
> In 'Learning Python' by Mark Lutz and David Ascher, on page 77 it makes
> mention of the 'sys.stdout.write' method. However, when I check this out,
I
> don't see the 'write' method in the list...
>
> >>> import sys
> >>> dir(sys.stdout)
> ['shell', 'softspace', 'tags']
>
> I must be doing something fundamentally wrong. :^(

This is what I see when I run Python in a commandbox:

D:\PySym>python
Python 2.0 (#8, Dec 18 2000, 13:10:05) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys.stdout)
['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read',
'readin
to', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate',
'write',
'writelines']
>>>

You may be using some other environment, where sys.stdout refers
to an object that's not a builtin file object; it will surely
have a write method, but it need not define it itself -- it can
delegate.  dir() does not consider such delegation, only the
dictionary of the object itself.

For example, your result is what I also get if I run this in
IDLE.


> I guess this brings up the bigger question of self help. Is there an easy
or
> prescribed way to find out what module (or class) a particular method is
> implemented in?

The Index and Search tabs of the (HTML Help version of) Python 2
docs are pretty good that way.  But, if you mean 'by reflection'...:

>>> w=getattr(sys.stdout,'write')
>>> w
<built-in method write of file object at 007C22F0>

in the Python at the command line; in IDLE, though:

>>> w=getattr(sys.stdout,'write')
>>> w
<method PseudoFile.write of PseudoFile instance at 00F47CEC>

Exploring further in IDLE we see:

>>> type(sys.stdout)
<type 'instance'>
>>> sys.stdout.__class__
<class PyShell.PseudoFile at 00F0F03C>
>>> dir(sys.stdout.__class__)
['__doc__', '__init__', '__module__', 'flush', 'isatty', 'write',
'writelines']
>>> sys.stdout.__class__.__bases__
()

which is about it -- it's pretty easy to automate this
'browsing', of course, but doing it by hand can be quite
educational.


> As a side (but related) issue, the current online reference material does
> not always indicate all of the exceptions thrown by a method or function.
> What is the best way to determine this when writing code?

Now THAT is something I think you can't get by reflection -- the
docs WOULD have to provide it, I think.


Alex






More information about the Python-list mailing list