[ python-Feature Requests-1155485 ] file() on a file

SourceForge.net noreply at sourceforge.net
Mon Mar 14 22:20:51 CET 2005

Feature Requests item #1155485, was opened at 2005-03-03 00:48
Message generated for change (Comment added) made by loewis
You can respond by visiting: 

Category: Python Interpreter Core
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Felix Lee (felixlee)
Assigned to: Nobody/Anonymous (nobody)
Summary: file() on a file

Initial Comment:
it would be nice if file(f) worked when f is already a
file, either by returning f or by constructing a new
file that refers to the same thing.  that would make it
easy to write functions that can take either a file or
a filename as an argument, like so:
    def p(f): print list(file(f))
which is kind of like using int() as a cast operation.


>Comment By: Martin v. Löwis (loewis)
Date: 2005-03-14 22:20

Logged In: YES 

The same argument can *not* be made for strings, since
strings are immutable, so it does not matter whether you get
the original thing or a copy. Also, str(x) invokes x's
__str__ conversion. For lists, the argument is also
different: list(x) requires an iterable object and creates a
list out of it. The notion of an iterable object is
well-defined, and if you pass something that is not
iterable, you get a TypeError.

For files, this is entirely different. file() does not take
one argument, but three (and two of them are optional). The
first (mandatory) argument is a "filename". It might be
debatable what precisely a file name is, and indeed you can
pass both byte strings and unicode strings. A file, most
certainly, is *not* a filename, and there is no notion of
"converting to a file" in Python (e.g. by means of
__file__). This just isn't a useful generalization.


Comment By: Felix Lee (felixlee)
Date: 2005-03-14 21:47

Logged In: YES 

that argument also works against str() and list().  it's not
obvious whether str(s) and list(v) should return itself, a
proxy, or a copy, and they're all useful in different
situations.  I don't think anyone would argue that the
ambiguity means those should be undefined.

I think file(f) is similar.  it has a few more issues
because files are special, but I think picking a reasonable
behavior for file(f) would simplify some programming. 
returning a dup is probably the least surprising in most
situations, because of f.close().


Comment By: Martin v. Löwis (loewis)
Date: 2005-03-13 23:53

Logged In: YES 

It's not at all obvious what this should do. Three
alternatives come to mind:
1. return f
2. return a wrapper object which delegates all calls
3. return a new file object, which is dup(2)'ed from the
original one.

Either of them might be meaningful in some context, and they
are mutually incompatible. In the face of ambiguity, refuse
the temptation to guess, so I'm -1.


You can respond by visiting: 

More information about the Python-bugs-list mailing list