2

I see people occasionally open a file handler with the file built in; Particularly in the pyyaml documentation.

This confuses me as the Python documentation states:

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

So this seems to imply that file and open do the same thing, yet file is a type, whereas open is a function:

>>> open
<built-in function open>
>>> file
<type 'file'>

And they both return a file type object:

>>> open('/dev/zero')
<open file '/dev/zero', mode 'r' at 0x7f9bb0b964b0>
>>> file('/dev/zero')
<open file '/dev/zero', mode 'r' at 0x7f9bb0b96540>

Is there a difference of using one or the other?

Are there caveats or advantages to using file vs open to open files?

ThorSummoner
  • 16,657
  • 15
  • 135
  • 147

1 Answers1

0

Yes, they do the same thing. Using one versus the other is simply a matter of style and readability; there are no other caveats or advantages in terms of behavior.

yole
  • 92,896
  • 20
  • 260
  • 197
  • 3
    Not quite true; `open` allows you to use it as a contextmanager in a `with` statement so that the file is properly closed reguardless of errors in your code that deals with that file. – aruisdante Mar 02 '15 at 18:49
  • 1
    `open` is a preferable way (factory vs constructor), besides, `file` was removed since 3.0. And, @aruisdante, `file` can also be used in context managers. – bereal Mar 02 '15 at 18:52
  • 1
    @bereal huh, sure enough it can. But I completely agree with your point about using a factory vs. a concrete type constructor, especially in a duck-typed dynamic language like Python. – aruisdante Mar 02 '15 at 18:53