nntplib, huge xover object

carroll at tjc.com carroll at tjc.com
Tue Apr 8 13:10:05 EDT 2003


On Mon, 07 Apr 2003 20:39:13 GMT, Robin Munn <rmunn at pobox.com> wrote:

>The two approaches you describe in the paragraph above are really the
>same approach, in a *slightly* different disguise. When you say "if the
>caller invoked it with the wrong object type, he'll get an error," I'm
>guessing that your idea of the "wrong object type" is an object that's
>not a subclass of "file". But in Python, the "wrong object type" would
>be... (drumroll)... Any object type that didn't have a method named
>"write"!

I don't look at it that way.  The doc for the method specifies that
the parameter is (if not a string) a file object.  That means that the
wrong object type is any object type that isn't a file object.

Now, it happens that the only other method used for this object is the
write method, but that's not guaranteed.  If someone called the method
using an object that is not a file object, but that has a write method
(e.g., a StringIO object), sure, it would work.  For now.  In this
release.  But if the nntp method were changed in the future to do
something else with the file object that actually depended on it being
a file object, it would fail.  

I submit that the failure is because the user is not passing it an
object of the type that it is documented to require, because it says
pretty plainly that it requires a file object, not merely any object
that includes a method named write.  Using a non-file object is just
something you can get away with.

>The key concept to understand is this: in Python, types usually don't
>matter. What matters is interfaces. If you have a function that expects
>to be passed a file object, for instance, someone could pass it a
>StringIO object (http://www.python.org/doc/2.2/lib/module-StringIO.html)
>instead. 

FWIW, nntplib will work with StringIO (or anything else that has a
write method) -- not because it does interface checking on the object
passed, but because, after it's type-checked whether it's a string
(and if it's a string, it creates a file object with open() on the
file named in the string), it assumes that any non-string object it's
been passed is a file object (if you rely on the docs) or a object
that supports write() (if you read the code), and goes ahead and uses
write().  If the object doesn't have a write method, you'll get an
exception.

In any event, I'm not planning on re-writing NNTPlib's file support --
I'm just extending its existing file support to some additional NNTP
commands.





More information about the Python-list mailing list