import inspect


def clean_object_stack(stack):
    """
    Join an object stack so that consecutive modules are merged into the last one.

    This avoids the stack [collections, collections.abc] as being named
    'collections.collections.abc'.

    >>> import collections
    >>> from collections import abc
    >>> clean_object_stack([collections, abc]) == [abc]
    True
    >>> from collections import Counter
    >>> input_stack = [collections, Counter, Counter.most_common]
    >>> clean_object_stack(input_stack) == input_stack
    True
    """
    assert isinstance(stack, list)

    stack = stack.copy()
    new_stack = []

    for obj in stack:
        # This one is a module, and the last one is a module
        # Therefore it must be a submodule, get rid of the first one
        # to avoid [collections, collections.abc]
        if new_stack and inspect.ismodule(obj) and inspect.ismodule(new_stack[-1]):
            new_stack.pop()
        new_stack.append(obj)

    assert len(new_stack) > 0
    return new_stack