cellannotation / cap-anndata

BSD 3-Clause "New" or "Revised" License
4 stars 0 forks source link

read_anndata_file as the part of package #3

Closed siberianisaev closed 5 months ago

siberianisaev commented 7 months ago
import logging
import contextlib
import h5py

from cap_anndata import CapAnnData

logger = logging.getLogger(__name__)

@contextlib.contextmanager
def read_anndata_file(file_path: str, edit: bool = False):
    mode = "r+" if edit else "r"
    logger.debug(f"Read file {file_path} mode={mode}...")

    try:
        file = h5py.File(file_path, mode)
        cap_adata = CapAnnData(file)
        logger.debug(f"Successfully read anndata file path {file_path}")
        yield cap_adata

    except Exception as error:
        logger.error(f"Error during read anndata file at path: {file_path}, error = {error}!")
        raise error

    finally:
        file.close()
        logger.debug("AnnData closed!")