Skip to content

Python 2.x 3.x compatibility notes

Alex Willmer edited this page Apr 20, 2026 · 12 revisions

Exceptions

Exception hierachy

Python <= 3.2

  • BaseException
    • Exception
      • StandardError
        • EnvironmentError
          • IOError
            • socket.error
          • OSError
      • select.error

Python >= 3.3

  • BaseException
    • Exception
      • OSError
        • BlockingIOError
        • EnvironmentError
        • IOError
        • select.error
        • socket.error

Refs

InterruptedError

Python 3.5+ automatically retries system calls that return EINTR.

Backports

Files

  • open(), os.fdopen(), etc return
    • file instances in Python 2.x
    • io.* instances in Python 3.x
  • io module requires Python >= 2.6
  • BlockingIOError requires Python >= 3.3 (first doc mention Python 3.4)

Non-blocking behaviour

In non-blocking mode, if n > 0 is specified, and no bytes are available

In-memory IO

  • cStringIO.StringIO (Python >= 1.2)

    • accepts mix of byte-strings and ascii encodable unicode.
    • Always outputs a byte-string.
    • cStringIO.StringIO(some_str) returns a read-only type, without a write() method.
    • cStringIO.StringIO() returns a read-write type.
  • StringIO.StringIO (Python >= 1.5)

    • accepts mix of byte-strings and unicode.
    • If any input is uncode, then output is unicode, otherwise output is byte-string.
    • If any input byte-string is not ascii encodable, then getvalue() raises UnicodeError.
  • io.BytesIO (Python >= 2.6)

    • accepts and returns byte-strings
    • Always same type, always readable and writable
  • io.StringIO (Python >= 2.6; native implementation Python >= 2.7)

    • accepts and returns unicode strings
    • Always same type, always readable and writable

See also https://github.com/mitogen-hq/mitogen/issues/1391, https://gist.github.com/moreati/6e0239e9057e8fda147ce12321011e5d

Special (dunder) methods

2.x returns 3.x returns
__bytes__ -- bytes
__repr__ bytes unicode string
__str__ bytes unicode string
__unicode__ unicode string --

subprocess

  • Python >= 2.4
  • Python >= 2.6: Popen.send_signal(s), Popen.terminate(), Popen.kill()
  • Python >= 3.3: Popen.communicate(..., timeout)

Clone this wiki locally