If *fp* is a #io.TextIOWrapper object, this function returns the underlying
  binary stream and the encoding of the IO-wrapper object. If *encoding* is not
  None and does not match with the encoding specified in the IO-wrapper, a
  #RuntimeError is raised.

def unpack_text_io_wrapper(fp, encoding):
  """
  If *fp* is a #io.TextIOWrapper object, this function returns the underlying
  binary stream and the encoding of the IO-wrapper object. If *encoding* is not
  None and does not match with the encoding specified in the IO-wrapper, a
  #RuntimeError is raised.
  """

  if isinstance(fp, io.TextIOWrapper):
    if fp.writable() and encoding is not None and fp.encoding != encoding:
      msg = 'TextIOWrapper.encoding({0!r}) != {1!r}'
      raise RuntimeError(msg.format(fp.encoding, encoding))
    if encoding is None:
      encoding = fp.encoding
    fp = fp.buffer

  return fp, encoding