[Python-Dev] file(fileinput.input())

Aahz aahz@pythoncraft.com
Mon, 6 May 2002 12:07:56 -0400


On Mon, May 06, 2002, Guido van Rossum wrote:
>Aahz:
>>
>> Should file(fileinput.input()) work?  Currently it raises an
>> exception because fileinput.input() returns neither a string nor a
>> buffer object.
> 
> What on earth would you want it to do?  It doesn't seem to make any
> sense to me.

Well, if it should work, it should return the FileInput instance (i.e.
return self).  On thinking further, I'm going to use a slightly
different question divorced from my current problem:

What should list(UserList()) return?  What about 

    class myList(list):
        pass
    l = list(myList())

I suppose this question is related to PEPs 245/246.  The broader
question is, what should a constructor return when called on a related
object or subclass?

Getting back to my specific example, I've got this function:

    def grep(f, regex):
        f = file(f)
        regex = re.compile(regex)
        for line in f:
            if regex.search(line):
                yield line

I was originally passing in file handles or filenames, demonstrating to
the students that calling a constructor on an existing object returns
that object if it doesn't need to do any real work.  Alex suggested that
I use fileinput.input(), whereupon my function blew up.

The meta question is, what kind of programming style do we want to push?
More smarts on top or bottom?
-- 
Aahz (aahz@pythoncraft.com)           <*>         http://www.pythoncraft.com/

See me at OSCON!  I'm teaching Python for [Perl] Programmers, a fast intro 
for all experienced programmers (not just Perl).  Early bird ends June 10.
http://conferences.oreillynet.com/os2002/