39

In the past, there's codecs which got replaced by io. Although it seems like it's more advisable to use io.open, most introductory python classes still teaches open.

There's a question with Difference between open and codecs.open in Python but is open a mere duck-type of io.open?

If not, why is it better to use io.open? And why is it easier to teach with open?

In this post (http://code.activestate.com/lists/python-list/681909/), Steven DAprano says that the built in open is using the io.open in the backend. So should we all refactored our code to use open instead of io.open?

Other than backward compatibility for py2.x, are there any reason to use io.open instead of open in py3.0?

Community
  • 1
  • 1
alvas
  • 115,346
  • 109
  • 446
  • 738
  • 2
    Check out `help(open)` and you'll see that it's the same as `io.open()` - even the heading says `Help on built-in function open in module io`, so in other words, there is no reason to use `io.open()` if you're writing a program in Python 3. – Tim Pietzcker Nov 24 '15 at 10:43
  • 1
    @TimPietzcker, `io.open` is only for backwards compatibility right? If so, I should start changing all the class materials for `python3` =) – alvas Nov 24 '15 at 10:45
  • 1
    Yes, probably. It makes porting from 2.x to 3.x easier, but if you're starting out with 3.x, there's no need to make this more complicated. – Tim Pietzcker Nov 24 '15 at 10:47
  • What brought me to this post: This is relevant for __ruff__ rule **UP020** (open-alias; Use builtin open) which is based on [`pyupgrade`](https://pypi.org/project/pyupgrade/)'s replacement of `io.open()` with `open()` in line with the accepted answer. – Matthias Arras Jan 23 '23 at 20:43

1 Answers1

43

Situation in Python3 according to the docs:

io.open(file, *[options]*)

This is an alias for the builtin open() function.

and

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module [i.e. codecs] provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files

(bold and italics are my edits)

Yan Foto
  • 10,850
  • 6
  • 57
  • 88
VPfB
  • 14,927
  • 6
  • 41
  • 75