from typing import Optional
import gzip


def _open(fname: str, mode: Optional[str] = "r"):
    """
    Return a function to open a (gzipped) file.

    Parameters
    ----------
    fname: str
        (gzipped) file path
    mode: str
        (r)ead or (w)rite.

    Returns
    -------
    generator
        opened file
    """
    if mode not in ["r", "w"]:
        raise ValueError("mode must be either 'r' or 'w'.")

    if fname.endswith(".gz"):
        return gzip.open(fname, mode + "t")
    return open(fname, mode)