import pkg_resources


def load_object(target, namespace=None):
    """This helper function loads an object identified by a dotted-notation string.

    For example:

        # Load class Foo from example.objects
        load_object('example.objects:Foo')

    If a plugin namespace is provided simple name references are allowed.  For example:

        # Load the plugin named 'routing' from the 'web.dispatch' namespace
        load_object('routing', 'web.dispatch')

    Providing a namespace does not prevent full object lookup (dot-colon notation) from working.
    """
    if namespace and ':' not in target:
        allowable = dict((i.name,  i) for i in pkg_resources.iter_entry_points(namespace))
        if target not in allowable:
            raise ValueError('Unknown plugin "' + target + '"; found: ' + ', '.join(allowable))
        return allowable[target].load()

    parts, target = target.split(':') if ':' in target else (target, None)
    module = __import__(parts)

    for part in parts.split('.')[1:] + ([target] if target else []):
        module = getattr(module, part)

    return module