[Python-Dev] file(fileinput.input())
John Machin
sjmachin@lexicon.net
Tue, 07 May 2002 07:28:31 +1000
07/05/2002 2:07:56 AM, Aahz <aahz@pythoncraft.com> wrote:
[snip]
>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.
Since when? Where is this documented? The following simple example concords
with the documentation -- "The first two arguments are the same as for
stdio's fopen(): filename is the file name to be opened," -- and seems to
flatly contradict you.
Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> foo = file(sys.stdout)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: coercing to Unicode: need string or buffer, file found
>>> bar = file(sys.stdin)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: coercing to Unicode: need string or buffer, file found
>>>
The fact that str('foo') -> 'foo' is due to the historical fact that str() started out as
a builtin str(42) -> '42' and very much later also became a constructor, NOT due to some
general rule that ctor(ctor(some_args)) == ctor(some_args).
>Alex suggested that
>I use fileinput.input(), whereupon my function blew up.
Was Alex expecting this to work or to fail?
>The meta question is, what kind of programming style do we want to push?
>More smarts on top or bottom?
A general 'rule' that a constructor should
accept an instance of the class and silently do nothing with it would be IMO a totally
unnecessary burden on the author of the constructor for no perceived gain.