from functools import cmp_to_key


def sort(array, comparison=None, key=None, reverse=False):
    """Sort `array` using optional `comparison`, `key`, and `reverse` options
    and return sorted `array`.

    Note:
        Python 3 removed the option to pass a custom comparison function and
        instead only allows a key function. Therefore, if a comparison
        function is passed in, it will be converted to a key function
        automatically using ``functools.cmp_to_key``.

    Args:
        array (list): List to sort.
        comparison (callable, optional): A custom comparison function used to
            sort the list. Function should accept two arguments and return a
            negative, zero, or position number depending on whether the first
            argument is considered smaller than, equal to, or larger than the
            second argument. Defaults to ``None``. This argument is mutually
            exclusive with `key`.
        key (callback, optional): A function of one argument used to extract a
            a comparison key from each list element. Defaults to ``None``. This
            argument is mutually exclusive with `comparison`.
        reverse (bool, optional): Whether to reverse the sort. Defaults to
            ``False``.

    Returns:
        list: Sorted list.

    Warning:
        `array` is modified in place.

    Example:

        >>> sort([2, 1, 4, 3])
        [1, 2, 3, 4]
        >>> sort([2, 1, 4, 3], reverse=True)
        [4, 3, 2, 1]
        >>> results = sort([{'a': 2, 'b': 1},\
                            {'a': 3, 'b': 2},\
                            {'a': 0, 'b': 3}],\
                           key=lambda item: item['a'])
        >>> assert results == [{'a': 0, 'b': 3},\
                               {'a': 2, 'b': 1},\
                               {'a': 3, 'b': 2}]

    .. versionadded:: 2.2.0
    """
    # pylint: disable=redefined-outer-name
    if comparison and key:
        raise Exception(
            'The "comparison" and "key" arguments are mutually exclusive')

    if comparison:
        key = cmp_to_key(comparison)

    array.sort(key=key, reverse=reverse)
    return array