def lookup_by_name(name, nsdicts):
    """
    Look up an object by name from a sequence of namespace dictionaries.
    Returns a tuple of (nsdict, obj_name, attrs); nsdict is the namespace
    dictionary the name was found in, obj_name is the name of the base object
    the name is bound to, and the attrs list is the chain of attributes
    of the object that completes the name.

        >>> import os
        >>> nsdict, obj_name, attrs = lookup_by_name("os.path.isdir", 
        ...     (locals(),))
        >>> obj_name, attrs
        ('os', ['path', 'isdir'])
        >>> getattr(getattr(nsdict[obj_name], attrs[0]), attrs[1])  # doctest: +ELLIPSIS
        <function isdir at ...>
        >>> lookup_by_name("os.monkey", (locals(),))
        Traceback (most recent call last):
          ...
        NameError: name 'os.monkey' is not defined

    """
    for nsdict in nsdicts:
        attrs = name.split('.')
        names = []
        while attrs:
            names.append(attrs.pop(0))
            obj_name = '.'.join(names)
            if obj_name in nsdict:
                attr_copy = attrs[:]
                tmp = nsdict[obj_name]
                try:
                    while attr_copy:
                        tmp = getattr(tmp, attr_copy.pop(0))
                except AttributeError:
                    pass
                else:
                    return nsdict, obj_name, attrs
    raise NameError("name '%s' is not defined" % name)
