nntplib, huge xover object
Robin Munn
rmunn at pobox.com
Sat Apr 5 13:11:50 EST 2003
carroll at tjc.com <carroll at tjc.com> wrote:
> Modified method works as follows:
>
> xover(start, end, [file])
> Return a pair (resp, list). list is a list of tuples, one for
> each article in the range delimited by the start and end
> article numbers. Each tuple is of the form (article number,
> subject, poster, date, id, references, size, lines).
>
> If the file parameter is specified, then the output is stored
> to a file rather than to list. If file is a string, then the
> method will open a file object with that name, write to it,
> then close it. If file is a file object, then it will start
> calling write() on it to store the lines returned by XOVER. If
> file is supplied, then the returned list is an empty list.
>
> This is an optional NNTP extension, and may not be supported
> by all servers.
A couple points.
First, from what you've written above, it sounds like you're doing
type-checking to determine whether the parameter is a string or a file.
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"
except AttributeError:
# No: it doesn't have a write() method. Is it a string?
try:
output_file.lstrip
print "output_file is a string-like object"
except AttributeError:
# Neither a file nor a string
raise ValueError, "output_file should be a file or a string"
Second, do *not* use the name "file" as your parameter name; you will
shadow the file builtin.
Third, I'm not sure I like the functionality of passing a string
filename. It sounds convenient, but all it really does is *add*
ambiguity to your function which could be avoided. Just let that
parameter be a file-like object that's already been opened for writing,
and do *not* close it when you're done. If the user really wants the
functionality you provide (open filename, write, close it when done),
they can do it as easily as this:
xover(start, end, open('foo.txt', 'w'))
See? File-like object gets created, passed to your function, and then
automatically garbage-collected (and thus closed) when your function
returns.
Other than that, nice job.
--
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