16
votes

Possible Duplicate:
Python - When to use file vs open

From the official python documentation,

http://docs.python.org/library/functions.html#file

When opening a file, it’s preferable to use open() instead of invoking this constructor directly

But it doesn't give a reason.

1
For starters, it is gone in Python 3. Though that's a consequence and reinforcement, not a reason. - user395760
I'm not positive on this, so I won't make an answer for it, but it may have to do with how Python handles the "with" keyword. I'm unsure if you can use "with" with a constructor. - MintGrowth
@Marcin One of the types in io. - user395760
@StormKiernan: both file and open work with the with-statement. Anything that defines correct __enter__(), __exit__() methods would work. - jfs

1 Answers

18
votes

The Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

So either file or open should go.

>>> type(file)
<type 'type'>
>>> type(open)
<type 'builtin_function_or_method'>

open is a function that can return anything. file() returns only file objects.

Though it seems open returns only file objects on Python 2. And before Python 2.5 file and open are the same object.

As @gnibbler suggested in the comments the original reason for the existence of file might be to use it as the name for base classes.

Also, file() in principle could return other types as for example int() did on earlier Python versions:

>>> type(int(2**64)) is long
True
>>> type(int()) is int
True
>>> int is long
False

This answer is very similar to @Ryan's answer.

In addition BDFL said:

"The file class is new in Python 2.2. It represents the type (class) of objects returned by the built-in open() function. Its constructor is an alias for open(), but for future and backwards compatibility, open() remains preferred." (emphasis mine)