nntplib, huge xover object

Mike Meyer mwm at mired.org
Sun Apr 6 13:14:11 EDT 2003


Robin Munn <rmunn at pobox.com> writes:
> carroll at tjc.com <carroll at tjc.com> wrote:
>     # 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"

If you're just going to check the attribute and not use it, why not
use hasattr?

        if hasattr(output_file, 'write'):
            print "output_file is a file-like object"
        elif hasattr(output_file, 'lstrip'):
            print "output file is a string-like object"
        else:
            raise ValueError, "output_file should be a file or a string"
          

> 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:

That's excellent advice, but...

>     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.

The garbage collection happening when your function returns is
implementation specific. It works that way in CPython, but not
Jython. You should always explicitly close files to make sure they get
closed - and the output flushed, in this case - when you're done with
them.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.




More information about the Python-list mailing list