def name_from_fp(fp):
    """Returns the name of the opened file held by fp, which can be either
    a regular file or a BZ2File.

    """
    if hasattr(fp, 'name'):
        return fp.name
    elif hasattr(fp, '_fp'):
        return fp._fp.name
    elif hasattr(fp, 'fp'):
        # the documentstore._open class
        return name_from_fp(fp.fp)
    else:
        raise ValueError("Can't find name of open file %r" % fp)