nntplib, huge xover object

Robin Munn rmunn at pobox.com
Mon Apr 7 16:39:13 EDT 2003


carroll at tjc.com <carroll at tjc.com> wrote:
> On Sat, 05 Apr 2003 18:11:50 GMT, Robin Munn <rmunn at pobox.com> wrote:
>>You may not be doing type-checking, in which case this advice doesn't
>>apply to you, but type-checking is the wrong way to go about that. Do
>>interface checking instead, e.g.:
>>
>>    # Is it a file-like object?
>>    try:
>>        output_file.write
>>        print "output_file is a file-like object"
> 
> Just curious; why is this preferred?  Serious question; I'm relatively
> new to Python, and still learning a lot.
> 
> I'm thinking it might be two different philosophies.  The one in the
> present nntplib will try to invoke write() in whatever object was
> passed to it, and if the caller invoked it with the wrong object type,
> he'll get an error.  The one above seems to change the spec to support
> any object that has a method named "write."

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"!

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. And it would just work, without your function needing to know
anything about the StringIO class -- because StringIO implements the
write(), read(), readline(), etc. methods. That's why in many places in
the documentation you'll see "Parameter foo is a file-like object..."

In statically-typed languages like Java, you would have to jump through
some hoops to get this kind of functionality. For example, you might
have an Interface called IFileLike. Your functions would expect a
parameter that satisfied IFileLike, and your classes like StringIO would
implement IFileLike. In Python, though, all you have to do is try to use
the write() method of the object you've been passed. That's it. The Java
paradigm, with formally defined interfaces, could be called Look Before
You Leap (LBYL), while the Python paradigm could be called Easier to Ask
Forgiveness than Permission (EAFP).

For more reading on this subject, look at the following recipe in the
Python Cookbook online:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list