from collections import defaultdict


def get_modules(module, grouped=False, sorted=True):
    """
    Retrieve @module actions from a python module.

    If *grouped*, return modules grouped by action tag.

    If *sorted*, sort the actions by name attribute, otherwise they appear
    in the original order in the module.
    """
    actions = [
        fn for name in dir(module)
        for fn in [getattr(module, name)]
        if hasattr(fn, 'group')
    ]
    if sorted:
        actions.sort(key=lambda fn: fn.__name__)
    if grouped:
        groups = defaultdict(list)
        for fn in actions:
            groups[fn.action].append(fn)
        return groups
    return actions