import gzip
import bz2
import lzma


def open_to_read(file, mode='rt'):
    """Version of 'open' that is smart about different types of compressed files
    and file-like objects that are already open to read.  'mode' has to be a
    valid read mode such as 'r', 'rb' or 'rt'.
    """
    assert mode in ('r', 'rb', 'rt'), 'illegal read mode'
    enc = 't' in mode and 'utf8' or None
    if isinstance(file, str) and file.endswith('.gz'):
        return gzip.open(file, mode, encoding=enc)
    elif isinstance(file, str) and file.endswith('.bz2'):
        return bz2.open(file, mode, encoding=enc)
    elif isinstance(file, str) and file.endswith('.xz'):
        return lzma.open(file, mode, encoding=enc)
    elif hasattr(file, 'read'):
        return file
    else:
        return open(file, mode)