<commit_before>"""
Module for reading and writing matlab (TM) .mat files
"""
# Authors: <NAME>, <NAME>

from __future__ import division, print_function, absolute_import
from contextlib import contextmanager
from scipy._lib.six import string_types

from .miobase import get_matfile_version, docfiller
from .mio4 import MatFile4Reader, MatFile4Writer
from .mio5 import MatFile5Reader, MatFile5Writer

__all__ = ['mat_reader_factory', 'loadmat', 'savemat', 'whosmat']


@contextmanager
def _open_file_context(file_like, appendmat, mode='rb'):
    f, opened = _open_file(file_like, appendmat, mode)
    yield f
    if opened:
        f.close()


def _open_file(file_like, appendmat, mode='rb'):
    """
    Open `file_like` and return as file-like object. First, check if object is
    already file-like; if so, return it as-is. Otherwise, try to pass it
    to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
    append '.mat' and try again.
    """
    if hasattr(file_like, 'read') and hasattr(file_like, 'write'):
        return file_like, False

    try:
        return open(file_like, mode), True
    except IOError:
        # Probably "not found"
        if isinstance(file_like, string_types):
            if appendmat and not file_like.endswith('.mat'):
                file_like += '.mat'
            return open(file_like, mode), True
        else:
            raise IOError('Reader needs file name or open file-like object')


@docfiller
def mat_reader_factory(file_name, appendmat=True, **kwargs):
    """
    Create reader for matlab .mat format files.

    Parameters
    ----------
    %(file_arg)s
    %(append_arg)s
    %(load_args)s
    %(struct_arg)s

    Returns
    -------
    matreader : MatFileReader object
       Initialized instance of MatFileReader class matching the mat file
       type detected in `filename`.<commit_msg>MAINT: only test for write attr if mode is wb<commit_after>"""
Module for reading and writing matlab (TM) .mat files
"""
# Authors: <NAME>, <NAME>

from __future__ import division, print_function, absolute_import
from contextlib import contextmanager
from scipy._lib.six import string_types

from .miobase import get_matfile_version, docfiller
from .mio4 import MatFile4Reader, MatFile4Writer
from .mio5 import MatFile5Reader, MatFile5Writer

__all__ = ['mat_reader_factory', 'loadmat', 'savemat', 'whosmat']


@contextmanager
def _open_file_context(file_like, appendmat, mode='rb'):
    f, opened = _open_file(file_like, appendmat, mode)
    yield f
    if opened:
        f.close()


def _open_file(file_like, appendmat, mode='rb'):
    """
    Open `file_like` and return as file-like object. First, check if object is
    already file-like; if so, return it as-is. Otherwise, try to pass it
    to open(). If that fails, and `file_like` is a string, and `appendmat` is true,
    append '.mat' and try again.
    """
    if hasattr(file_like, 'read'):
        if 'w' in mode and hasattr(file_like, 'write') is False:
            raise IOError("The file-like object does not have a write attribute")
        return file_like, False

    try:
        return open(file_like, mode), True
    except IOError:
        # Probably "not found"
        if isinstance(file_like, string_types):
            if appendmat and not file_like.endswith('.mat'):
                file_like += '.mat'
            return open(file_like, mode), True
        else:
            raise IOError('Reader needs file name or open file-like object')


@docfiller
def mat_reader_factory(file_name, appendmat=True, **kwargs):
    """
    Create reader for matlab .mat format files.

    Parameters
    ----------
    %(file_arg)s
    %(append_arg)s
    %(load_args)s
    %(struct_arg)s

    Returns
    -------
    matreader : MatFileReader object
       Initialized instance of MatFileReader class matching the mat file
       type detected in `filename`.
{'fraction_non_alphanumeric': 0.10222905457340507, 'fraction_numerical': 0.0030745580322828594, 'mean_word_length': 3.087958115183246, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '476892', 'n_tokens_mistral': 1188, 'n_tokens_neox': 1165, 'n_words': 396}