import typing
import itertools


def groupby(itr: typing.Iterable[typing.Any],
            key_fn: typing.Optional[typing.Callable[..., typing.Any]] = None
            ) -> typing.Iterable[
                typing.Tuple[typing.Any, typing.Iterable[typing.Any]]
            ]:
    """
    An wrapper function around itertools.groupby to sort each results.

    :param itr: Iterable object, a list/tuple/genrator, etc.
    :param key_fn: Key function to sort 'itr'.
    """
    return itertools.groupby(sorted(itr, key=key_fn), key=key_fn)